在Vue.js 中,使用axios 并且使用了ElementUI, 一般来说,文件上传有两种不同的实现方案:
首先后端需要提供文件上传的接口 以SpringBoot 为例
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
@PostMapping("/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("上传成功!");
}
这里的文件上传比较简单,上传的文件按照日期进行归类,使用 UUID 给文件重命名。
这里为了简化代码,我省略掉了异常捕获,上传结果直接返回成功,后端代码大伙可根据自己的实际情况自行修改
在 Vue 中,通过 Ajax 实现文件上传,方案和传统 Ajax 实现文件上传基本上是一致的,唯一不同的是查找元素的方式。
<input type="file" ref="myfile">
<el-button @click="importData" type="success" size="mini" icon="el-icon-upload2">导入数据</el-button>
在这里,首先提供一个文件导入 input 组件,再来一个导入按钮,在导入按钮的事件中来完成导入的逻辑。
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);
}
})
}
关于这段上传核心逻辑,解释如下:
这种文件上传方式,实际上就是传统的 Ajax 上传文件,和大家常见的 jQuery 中写法不同的是,这里元素查找的方式不一样(实际上元素查找也可以按照JavaScript 中原本的写法来实现),其他写法一模一样。这种方式是一个通用的方式,和使用哪一种前端框架无关。最后再和大家来看下封装的上传方法:
export const uploadFileRequest = (url, params) => {
return axios({
method: 'post',
url: `${base}${url}`,
data: params,
headers: {
'Content-Type': 'multipart/form-data'
}
});
}
经过这几步的配置后,前端就算上传完成了,可以进行文件上传了。
如果使用 Upload ,则需要引入 ElementUI,所以一般建议,如果使用了 ElementUI 做 UI 控件的话,则可以考虑使用 Upload 组件来实现文件上传,如果没有使用 ElementUI 的话,则不建议使用 Upload 组件,至于其他的 UI 控件,各自都有自己的文件上传组件,具体使用可以参考各自文档。
<el-upload
style="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>
onSuccess(response, file, fileList) {
this.enabledUploadBtn = true;
this.uploadBtnIcon = 'el-icon-upload2';
this.btnText = '数据导入';
},
onError(err, file, fileList) {
this.enabledUploadBtn = true;
this.uploadBtnIcon = 'el-icon-upload2';
this.btnText = '数据导入';
},
beforeUpload(file) {
this.enabledUploadBtn = false;
this.uploadBtnIcon = 'el-icon-loading';
this.btnText = '正在导入';
}
两种上传方式各有优缺点:
参考 :[https://segmentfault.com/a/1190000019012180]