SpringBoot+微信小程序?qū)崿F(xiàn)文件上傳與下載功能詳解
1、文件上傳
1.1 后端部分
1.1.1 引入Apache Commons FIleUpload組件依賴
<!--文件上傳與下載相關(guān)的依賴-->
<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 設(shè)置上傳文件大小限制
在application.yml(根據(jù)個(gè)人情況,有的人可能用的properties)配置文件中添加如下參數(shù):

1.1.3 創(chuàng)建控制器
后端部分很簡單,就是實(shí)現(xiàn)文件上傳而已,這個(gè)學(xué)過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();
}
//將上傳文件保存到一個(gè)目標(biāo)文件中
file.transferTo(filePath);
return "success";
}
return "fail";
}
這里為了方便,我直接使用了絕對路徑,生產(chǎn)環(huán)境中是不允許的。
1.2 小程序前端部分
wx.uploadFile(OBJECT)接口將本地資源上傳到開發(fā)者的服務(wù)器上,客戶端發(fā)起一個(gè)HTTPS的Post請求,其中content-type為multipart/form-data。在上傳之前需要先獲取本地(手機(jī))上的資源,即使用wx.uploadFile(OBJECT)之前應(yīng)該先調(diào)用其他的接口來獲取待上傳的文件資源,例如先調(diào)用wx.chooseImage()接口來獲取到本地圖片資源的臨時(shí)文件路徑,再通過wx.uploadFile(OBJECT)接口將本地資源上傳到指定服務(wù)器。wx.uploadFile()接口屬性如下表所示。

官網(wǎng)示例代碼:
wx.chooseImage({
success (res) {
const tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: 'https://example.weixin.qq.com/upload', //僅為示例,非真實(shí)的接口地址
filePath: tempFilePaths[0],
name: 'file',
formData: {
'user': 'test'
},
success (res){
const data = res.data
//do something
}
})
}
})
真實(shí)的前端代碼如下:
pages/uploadFile/uploadFile.wxml
<!--index.wxml--> <view class="container"> <button bindtap='upfile'>選擇上傳文件</button> </view>
pages/uploadFile/uploadFile.js
//index.js
//獲取應(yīng)用實(shí)例
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 實(shí)現(xiàn)效果
編譯之后:

點(diǎn)擊上傳文件,隨便選擇一張圖片



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

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

官網(wǎng)示例代碼:

下載的前端代碼如下:
這里實(shí)現(xiàn)兩個(gè)功能,一個(gè)實(shí)現(xiàn)把下載到的圖片設(shè)置為頭像,另一個(gè)將圖片保存到手機(jī)本地。
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
//獲取應(yīng)用實(shí)例
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
//調(diào)用應(yīng)用實(shí)例的方法獲取全局?jǐn)?shù)據(jù)
app.getUserInfo(function(userInfo){
//更新數(shù)據(jù)
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()中調(diào)用了wx.downloadFile()接口,下載成功,圖片就會(huì)保存在res.tempFilePath中,再把res.tempFilePath設(shè)置為頭像。在函數(shù)dian2中,通過wx.saveImageToPhotosAlbum()接口把下載成功的圖片保存到系統(tǒng)相冊。
2.3 實(shí)現(xiàn)效果

這個(gè)圖片是直接從服務(wù)器上下載的,可以點(diǎn)擊下載將這個(gè)圖片保存到本地

到這里,文件上傳和下載就基本做完了。其實(shí)大多數(shù)都是后端的事情,接口寫好就沒啥大問題。不放心的可以先用swagger測試。
所有接口文檔均來自官網(wǎng)
以上就是SpringBoot+微信小程序?qū)崿F(xiàn)文件上傳與下載功能詳解的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot 小程序文件上傳下載的資料請關(guān)注腳本之家其它相關(guān)文章!
- SpringBoot+ruoyi框架文件上傳和下載的實(shí)現(xiàn)
- SpringBoot實(shí)現(xiàn)文件上傳下載實(shí)時(shí)進(jìn)度條功能(附源碼)
- springboot整合minio實(shí)現(xiàn)文件上傳與下載且支持鏈接永久訪問
- springboot+vue實(shí)現(xiàn)文件上傳下載
- springboot操作阿里云OSS實(shí)現(xiàn)文件上傳,下載,刪除功能
- 詳解SpringBoot下文件上傳與下載的實(shí)現(xiàn)
- SpringBoot 文件上傳和下載的實(shí)現(xiàn)源碼
- SpringBoot后臺實(shí)現(xiàn)文件上傳下載
- SpringBoot集成Hadoop實(shí)現(xiàn)文件的上傳和下載功能
相關(guān)文章
java不同版本在多線程中使用隨機(jī)數(shù)生成器的實(shí)現(xiàn)
本文主要介紹了java不同版本在多線程中使用隨機(jī)數(shù)生成器的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04
Springboot Druid 自定義加密數(shù)據(jù)庫密碼的幾種方案
這篇文章主要介紹了Springboot Druid 自定義加密數(shù)據(jù)庫密碼的步驟,幫助大家更好的理解和使用springboot,感興趣的朋友可以了解下2020-12-12
IntelliJ IDEA 創(chuàng)建spring boot 的Hello World 項(xiàng)目(圖解)
這篇文章主要介紹了IntelliJ IDEA 創(chuàng)建spring boot 的Hello World 項(xiàng)目的步驟詳解,需要的朋友可以參考下2018-01-01

