这篇文章主要介绍微信小程序如何实现上传图片,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
一 小程序端
user.wxml
<view class='user_head'>
<view>
<image src='{{ptuser.avatarUrl}}' bindtap='updateHead'></image>
</view>
<text>点击选择头像</text>
</view>
user.js
// 更换头像
span > updateHead: function () {
var that = this
// 上传图片 获取路径
wx.chooseImage({
success: function (res) {
console.log('临时路径:' + res.tempFilePaths[0])
wx.uploadFile({
url: app.globalData.baseUrl + '/file/uploadFile',
filePath: res.tempFilePaths[0],
name: 'file',
success: function (result) {
console.log("返回路径:" + result.data)
}
})
},
})
},
二 java端
package cn.helloxhs.moudle.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import cn.helloxhs.base.controller.BaseController;
@Controller
@RequestMapping("/file")
public class FileController extends BaseController {
@RequestMapping("/uploadFile")
@ResponseBody
public Object uploadFile(HttpServletResponse response, HttpServletRequest request, MultipartFile file) {
String realPath = request.getSession().getServletContext().getRealPath("/temp");
try {
CommonsMultipartFile cf = (CommonsMultipartFile) file;
DiskFileItem fi = (DiskFileItem) cf.getFileItem();
File f1 = fi.getStoreLocation();
InputStream ips = new FileInputStream(f1);
OutputStream ops = new FileOutputStream(realPath + "/" + "xhs.jpg");
byte[] b = new byte[1024];
int len;
try {
while ((len = ips.read(b)) != -1) {
ops.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 完毕,关闭所有链接
try {
ops.close();
ips.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return realPath;
}
}
图片存在了项目的temp目录下
以上是“微信小程序如何实现上传图片”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注编程网行业资讯频道!