SpringBoot+微信小程序實現(xiàn)文件上傳與下載功能詳解
1、文件上傳
1.1 后端部分
1.1.1 引入Apache Commons FIleUpload組件依賴
<!--文件上傳與下載相關的依賴-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
1.1.2 設置上傳文件大小限制
在application.yml(根據個人情況,有的人可能用的properties)配置文件中添加如下參數(shù):

1.1.3 創(chuàng)建控制器
后端部分很簡單,就是實現(xiàn)文件上傳而已,這個學過SpringMVC就行。
@ApiOperation("文件上傳")
@PostMapping("/upload")
public String upload(HttpServletRequest request, @RequestParam("file") MultipartFile file) throws IOException {
if(!file.isEmpty()){
//上傳文件路徑
// String path = request.getServletContext().getRealPath("/uploadFiles/");
String path="E:/upload";
//獲得上傳文件名
String fileName = file.getOriginalFilename();
File filePath = new File(path + File.separator + fileName);
System.out.println(filePath);
//如果文件目錄不存在,創(chuàng)建目錄
if(!filePath.getParentFile().exists()){
filePath.getParentFile().mkdirs();
}
//將上傳文件保存到一個目標文件中
file.transferTo(filePath);
return "success";
}
return "fail";
}
這里為了方便,我直接使用了絕對路徑,生產環(huán)境中是不允許的。
1.2 小程序前端部分
wx.uploadFile(OBJECT)接口將本地資源上傳到開發(fā)者的服務器上,客戶端發(fā)起一個HTTPS的Post請求,其中content-type為multipart/form-data。在上傳之前需要先獲取本地(手機)上的資源,即使用wx.uploadFile(OBJECT)之前應該先調用其他的接口來獲取待上傳的文件資源,例如先調用wx.chooseImage()接口來獲取到本地圖片資源的臨時文件路徑,再通過wx.uploadFile(OBJECT)接口將本地資源上傳到指定服務器。wx.uploadFile()接口屬性如下表所示。

官網示例代碼:
wx.chooseImage({
success (res) {
const tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'https://example.weixin.qq.com/upload', //僅為示例,非真實的接口地址
filePath: tempFilePaths[0],
name: 'file',
formData: {
'user': 'test'
},
success (res){
const data = res.data
//do something
}
})
}
})
真實的前端代碼如下:
pages/uploadFile/uploadFile.wxml
<!--index.wxml--> <view class="container"> <button bindtap='upfile'>選擇上傳文件</button> </view>
pages/uploadFile/uploadFile.js
//index.js
//獲取應用實例
var app = getApp()
Page({
data: {
},
//事件處理函數(shù)
upfile: function() {
console.log("--bindViewTap--")
wx.chooseImage({
success: function(res) {
var tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'http://127.0.0.1:8001/file/upload',
header: { "Content-Type": "multipart/form-data" },
filePath: tempFilePaths[0],
name: 'file',
formData:{
},
success(res){
console.log(res.data);
}
})
}
})
},
onLoad: function () {
}
})
1.3 實現(xiàn)效果
編譯之后:

點擊上傳文件,隨便選擇一張圖片



可以看到,前端和后端項目的控制臺都有對應的輸出。
然后去對應的路徑下面查找我們剛剛上傳的文件

2、文件下載
2.1 后端部分
這里依賴和設置上傳文件大小和上傳部分一致,不重復了。
2.1.1 控制器
@ApiOperation("文件下載")
@GetMapping("download")
public ResponseEntity<byte[]> download(HttpServletRequest request,@RequestParam("file") String fileName) throws IOException {
//下載文件路徑
String path="E:/upload";
//構建將要下載的文件對象
File file = new File(path + File.separator + fileName);
//設置響應頭
HttpHeaders headers=new HttpHeaders();
//下載顯示的文件名,解決中文名稱亂碼問題
String downloadFileName=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
//通知瀏覽器以下載方式(attachment)打開文件
headers.setContentDispositionFormData("attachment",downloadFileName);
//定義以二進制流數(shù)據(最常見的文件下載)的形式下載返回文件數(shù)據
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//使用spring mvc框架的ResponseEntity對象封裝返回下載數(shù)據
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
}
2.2 小程序前端部分
wx.downloadFile(Object object)下載文件資源到本地(手機).客戶端直接發(fā)起一個HTTPS GET請求,返回文件的本地臨時路徑。因為是臨時路徑,也就意味著用戶不會直到真實的文件目錄,所以下載到臨時路徑之后應該馬上做后續(xù)的工作,例如把臨時圖片設置為頭像,或者把臨時文件通過別的接口真是保存到手機指定目錄下。wx.downloadFile(Object object)參數(shù)如表所示。

官網示例代碼:

下載的前端代碼如下:
這里實現(xiàn)兩個功能,一個實現(xiàn)把下載到的圖片設置為頭像,另一個將圖片保存到手機本地。
pages/downloadFile/downloadFile.wxml
<!--index.wxml-->
<view class="container">
<view bindtap="dian" class="userinfo">
<image class="userinfo-avatar" src="{{avatar}}" background-size="cover"></image>
<text class="userinfo-nickname">{{userInfo.nickName}}</text>
</view>
<view class="usermotto">
<image src='http://127.0.0.1:8001/file/download?file=ymwtyNjpeZq645b1d185a17eaa9a65398443fbc4f8dd.jpg' class="tu"></image>
<view bindtap='dian2'>下載上圖</view>
</view>
</view>
pages/downloadFile/downloadFile.js
//index.js
//獲取應用實例
var app = getApp()
Page({
data: {
motto: 'Hello World',
userInfo: {},
avatar:null
},
//事件處理函數(shù)
dian: function() {
console.log("--bindViewTap--")
var that = this;
wx.downloadFile({
// url: 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3018968254,2801372361&fm=26&gp=0.jpg',
url:'http://127.0.0.1:8001/file/download?file=ymwtyNjpeZq645b1d185a17eaa9a65398443fbc4f8dd.jpg',
type: 'image',
success: function(res) {
console.log(res)
that.setData({avatar:res.tempFilePath})
}
})
},
onLoad: function () {
console.log('onLoad')
var that = this
//調用應用實例的方法獲取全局數(shù)據
app.getUserInfo(function(userInfo){
//更新數(shù)據
that.setData({
userInfo:userInfo
})
})
},
dian2: function () {
wx.downloadFile({
url:'http://127.0.0.1:8001/file/download?file=ymwtyNjpeZq645b1d185a17eaa9a65398443fbc4f8dd.jpg',
success: function (res) {
console.log(res);
var rr = res.tempFilePath;
wx.saveImageToPhotosAlbum({
filePath: rr,
success(res) {
wx.showToast({
title: '保存成功',
icon: 'success',
duration: 2000
})
}
})
}
})
}
})
在函數(shù)dian()中調用了wx.downloadFile()接口,下載成功,圖片就會保存在res.tempFilePath中,再把res.tempFilePath設置為頭像。在函數(shù)dian2中,通過wx.saveImageToPhotosAlbum()接口把下載成功的圖片保存到系統(tǒng)相冊。
2.3 實現(xiàn)效果

這個圖片是直接從服務器上下載的,可以點擊下載將這個圖片保存到本地

到這里,文件上傳和下載就基本做完了。其實大多數(shù)都是后端的事情,接口寫好就沒啥大問題。不放心的可以先用swagger測試。
所有接口文檔均來自官網
以上就是SpringBoot+微信小程序實現(xiàn)文件上傳與下載功能詳解的詳細內容,更多關于SpringBoot 小程序文件上傳下載的資料請關注腳本之家其它相關文章!
相關文章
詳解Spring MVC如何測試Controller(使用springmvc mock測試)
這篇文章主要介紹了詳解Spring MVC如何測試Controller(使用springmvc mock測試),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12
詳解Java編程中包package的內容與包對象的規(guī)范
這篇文章主要介紹了Java編程中包package的內容與包對象的規(guī)范,是Java入門學習中的基礎知識,需要的朋友可以參考下2015-12-12

