1.编写springBoot后台
控制层代码编写,。
/**
* 文件上传
* @param file
* @return
* @throws Exception
*/
@ResponseBody
@RequestMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file,@RequestParam(name = "fileName",required=false) String fileName
) throws Exception{
//fileName是你前台传参时的文件名字,也可以不指定
//不指定名字,保存时使用 file.getOriginalFilename()得到文件名字;
System.out.println("接收到文件");
//保存到文件服务器,OSS服务器
file.transferTo(new File("你想要保存的文件路径,相对路径或绝对路径"+fileName));
return "上传文件成功";
}
比如我设置的文件保存目录为,这是springBoot的静态资源保存位置,设置这个目录话,下载文件的时候,直接指定这个目录下的文件名字,如下载时候的url可指定为,可以不用再写下载文件的控制层了。
url: 'http://localhost:8080/file/12.jpg'
2 .微信小程序页面编写
文件上传的wxml页面:
<view>
<image wx:if="{{src}}" src="{{src}}"></image>
<button bindtap="choose" >选择文件</button>
<button bindtap="uploadFile">上传文件</button>
</view>
js文件:
data: {
src:''
},
choose:function(){
var that=this;
wx.chooseImage({
count:1,
sizeType:['original','compressed'],
sourceType:['album','camera'],
success:(res)=>{
let src=res.tempFilePaths[0];
console.log(src);
that.setData({
src:src
})
}
})
},
uploadFile:function(){
var that=this;
let src=this.data.src;
if(src==''){
wx.showToast({
title: '请选择文件',
icon:'none'
})
}
//准备上传文件
else{
console.log(src);
var fileName="12.jpg";//保存的文件名字,自定义
var uploadTask=wx.uploadFile({
url: 'http://localhost:8080/upload?fileName='+fileName,
header: {
"Content-Type": "multipart/form-data" },//类型
filePath: src,
name: 'file',//和后台接收的参数名字一致
success:(res)=>{
console.log(res.data);
wx.showToast({
title: '上传成功',
})
},
fail:function(res){
console.log("错误"+res);
}
})
uploadTask.onProgressUpdate((res)=>{
console.log('上传进度',res.progress);
console.log('已经上传的数据长度',res.totalBytesSent);
console.log('预期需要上传的数据总长度',res.totalBytesExpectedToSend);
})
}
}
文件下载的wxml页面:
<block wx:if="{{ isDownload}}">
<image src="{{src}}"></image>
</block>
<button bindtap="downlaod">文件下载</button>
文件下载的js:
data: {
isDownload:false
},
downlaod:function(){
console.log("下载");
var that=this;
var downTask=wx.downloadFile({
url: 'http://localhost:8080/file/要下载的文件名字',
success:function(res){
if(res.statusCode===200){
let src=res.tempFilePath;
that.setData({
src:src,
isDownload:true
})
}
},
fail:function(res){
console.log("下载失败!"+res);
}
})
downTask.onProgressUpdate((res)=>{
console.log('下载进度',res.progress);
console.log('已经下载的总数据长度',res.totalBytesWritten);
console.log('预期需要下载的数据长度',res.totalBytesExpectedToWrite);
})
},
3.页面截图
文件上传页面,可以看到,上传成功后,后台的数据响应给了小程序端。
下载文件页面,下载文件成功后,会将图片显示到当前页面。