这两天一直在处理微信小程序,在处理上传文件这一块遇到了一些 难题,也是在网上这种查阅资料,最后终于把效果做了出来
微信小程序官方文档也是提供了专门上传文件的接口~~~
1.这是选中图片方法
/**上传图片 */
uploader: function () {
var that = this;
//小程序自带的选中图片接口
wx.chooseImage({
count: 5, //最多可以选择的图片总数
// 可以指定是原图还是压缩图,默认二者都有
sizeType: ['original', 'compressed'],
// 可以指定来源是相册还是相机,默认二者都有
sourceType: ['album', 'camera'],
success: function (res) {
console.log(res);
wx.showToast({
title: '正在上传...',
icon: 'loading',
mask: true,
duration: 500
})
//这里会拿到所有图片的路径,保存下来为后面 使用
var tempFilePaths = res.tempFilePaths
that.setData({
tempFilePaths: tempFilePaths
})
}
},
2.这是上传后台接口
uploadFiles: function () {
var that = this;
//将保存的图片路径用来循环
if (that.data.tempFilePaths!=null){
for (var i = 0; i < that.data.tempFilePaths.length; i++) {
//小程序自带的上传图片接口
wx.uploadFile({
url: path + '***/uploadImage',
filePath: that.data.tempFilePaths[i],
name: 'file',
formData: {
fileId: fileId
},
header: {
"Content-Type": "multipart/form-data"
},
success: function (res) {
console.log(res);
}, fail: function (err) {
console.log()
}
})
}
}else{
console.log("没有上传图片")
}
},
3.wxml代码~~
<view class="img_in">
<view class='v1' wx:for="{{tempFilePaths}}" wx:key="">
<image src="{{item}}" mode="aspecFill" style="width: 200rpx; height: 200rpx" />
</view>
<image src='../images/publish.jpg' style="width: 200rpx; height: 200rpx" bindtap="uploader">获取图片</image>
</view>
4.最后是java的代码
@PostMapping(value = "/uploadImage")
public ModelAndView uploadImage(HttpServletRequest request,String fileId) throws IOException {
MultipartHttpServletRequest req =(MultipartHttpServletRequest)request;
MultipartFile file= req.getFile("file");
System.out.println("进入方法!"+file);
//获取文件名称的后缀信息
String fileOrginPath = file.getOriginalFilename();
//拆分文件路径信息
String[] ext1=fileOrginPath.split("\\.");
String ext =fileOrginPath.split("\\.")[ext1.length-1];
if(StringUtils.isEmpty(fileName)){
fileName = System.currentTimeMillis()+"";
}
//获取文件名
fileName +="."+ext;
//文件重命名
String pathName=sdf.format(new Date());
//项目文件存储地址
// String path = request.getServletContext().getRealPath(pathName);
String path = "C:/***/" + pathName; //本地文件存储地址
//创建新的文件夹来保存图片
File newFile = new File(path);
if(newFile.exists() == false){
newFile.mkdirs();
}
newFile = new File(newFile, fileName);
file.transferTo(newFile);
return null;
}
最后是 给你们看演示效果~~~