Spring Boot + Vue 前后端分离,两种文件上传方式总结
在Vue.js 中,如果網(wǎng)絡(luò)請(qǐng)求使用 axios ,并且使用了 ElementUI 庫(kù),那么一般來(lái)說(shuō),文件上傳有兩種不同的實(shí)現(xiàn)方案:
兩種方案,各有優(yōu)缺點(diǎn),我們分別來(lái)看。
準(zhǔn)備工作
首先我們需要一點(diǎn)點(diǎn)準(zhǔn)備工作,就是在后端提供一個(gè)文件上傳接口,這是一個(gè)普通的 Spring Boot 項(xiàng)目,如下:
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/"); ("/import") public RespBean importData(MultipartFile file, HttpServletRequest req) throws IOException {String format = sdf.format(new Date());String realPath = req.getServletContext().getRealPath("/upload") + format;File folder = new File(realPath);if (!folder.exists()) {folder.mkdirs();}String oldName = file.getOriginalFilename();String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));file.transferTo(new File(folder,newName));String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/upload" + format + newName;System.out.println(url);return RespBean.ok("上傳成功!"); } 復(fù)制代碼這里的文件上傳比較簡(jiǎn)單,上傳的文件按照日期進(jìn)行歸類(lèi),使用 UUID 給文件重命名。
這里為了簡(jiǎn)化代碼,我省略掉了異常捕獲,上傳結(jié)果直接返回成功,后端代碼大伙可根據(jù)自己的實(shí)際情況自行修改。
Ajax 上傳
在 Vue 中,通過(guò) Ajax 實(shí)現(xiàn)文件上傳,方案和傳統(tǒng) Ajax 實(shí)現(xiàn)文件上傳基本上是一致的,唯一不同的是查找元素的方式。
<input type="file" ref="myfile"> <el-button @click="importData" type="success" size="mini" icon="el-icon-upload2">導(dǎo)入數(shù)據(jù)</el-button> 復(fù)制代碼在這里,首先提供一個(gè)文件導(dǎo)入 input 組件,再來(lái)一個(gè)導(dǎo)入按鈕,在導(dǎo)入按鈕的事件中來(lái)完成導(dǎo)入的邏輯。
importData() {let myfile = this.$refs.myfile;let files = myfile.files;let file = files[0];var formData = new FormData();formData.append("file", file);this.uploadFileRequest("/system/basic/jl/import",formData).then(resp=>{if (resp) {console.log(resp);}}) } 復(fù)制代碼關(guān)于這段上傳核心邏輯,解釋如下:
這種文件上傳方式,實(shí)際上就是傳統(tǒng)的 Ajax 上傳文件,和大家常見(jiàn)的 jQuery 中寫(xiě)法不同的是,這里元素查找的方式不一樣(實(shí)際上元素查找也可以按照J(rèn)avaScript 中原本的寫(xiě)法來(lái)實(shí)現(xiàn)),其他寫(xiě)法一模一樣。這種方式是一個(gè)通用的方式,和使用哪一種前端框架無(wú)關(guān)。最后再和大家來(lái)看下封裝的上傳方法:
export const uploadFileRequest = (url, params) => {return axios({method: 'post',url: `${base}${url}`,data: params,headers: {'Content-Type': 'multipart/form-data'}}); } 復(fù)制代碼經(jīng)過(guò)這幾步的配置后,前端就算上傳完成了,可以進(jìn)行文件上傳了。
使用 Upload 組件
如果使用 Upload ,則需要引入 ElementUI,所以一般建議,如果使用了 ElementUI 做 UI 控件的話(huà),則可以考慮使用 Upload 組件來(lái)實(shí)現(xiàn)文件上傳,如果沒(méi)有使用 ElementUI 的話(huà),則不建議使用 Upload 組件,至于其他的 UI 控件,各自都有自己的文件上傳組件,具體使用可以參考各自文檔。
<el-uploadstyle="display: inline":show-file-list="false":on-success="onSuccess":on-error="onError":before-upload="beforeUpload"action="/system/basic/jl/import"><el-button size="mini" type="success" :disabled="!enabledUploadBtn" :icon="uploadBtnIcon">{{btnText}}</el-button> </el-upload> 復(fù)制代碼相應(yīng)的回調(diào)如下:
onSuccess(response, file, fileList) {this.enabledUploadBtn = true;this.uploadBtnIcon = 'el-icon-upload2';this.btnText = '數(shù)據(jù)導(dǎo)入'; }, onError(err, file, fileList) {this.enabledUploadBtn = true;this.uploadBtnIcon = 'el-icon-upload2';this.btnText = '數(shù)據(jù)導(dǎo)入'; }, beforeUpload(file) {this.enabledUploadBtn = false;this.uploadBtnIcon = 'el-icon-loading';this.btnText = '正在導(dǎo)入'; } 復(fù)制代碼上傳效果圖如下:
總結(jié)
兩種上傳方式各有優(yōu)缺點(diǎn):
關(guān)注公眾號(hào)牧碼小子,專(zhuān)注于 Spring Boot+微服務(wù),定期視頻教程分享,關(guān)注后回復(fù) Java ,領(lǐng)取松哥為你精心準(zhǔn)備的 Java 干貨!
轉(zhuǎn)載于:https://juejin.im/post/5cc518186fb9a03234165172
總結(jié)
以上是生活随笔為你收集整理的Spring Boot + Vue 前后端分离,两种文件上传方式总结的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: typescript 接口 inter
- 下一篇: Vue和其他框架的区别