使用uniapp一次性上传多个附件,一次提交,避免使用for循环进行提交。本文只实现逻辑,没有进行代码及页面优化。
uniapp上传附件:建立上传按钮,并指定click事件,在click事件中调用如下代码:
uni.uploadFile();方法详细使用请参考官方文档:
uni.uploadFile(OBJECT) | uni-app官网
let token = getToken()
let header = {}
header.Authorization = 'Bearer ' +token;
uni.chooseFile({
success: function (res) {
let tempFilePaths = res.tempFilePaths
let tempFiles = res.tempFiles
let fileDatas = new Array();
for(let i=0;i<tempFilePaths.length;i++){
let obj = {};
obj.name = tempFiles[i].name;
// obj.file = tempFilePaths[i]
obj.uri = tempFilePaths[i]
fileDatas.push(obj)
}
uni.uploadFile({
url: config.baseUrl + '/app/file/uploads', //仅为示例,非真实的接口地址
files: fileDatas,
// filePath: tempFilePaths[0],
// name: 'file',
header: header,
formData: {
'user': 'test'
},
success: (uploadFileRes) => {
console.log(uploadFileRes.data);
},
fail: (err) => {
console.log(err)
}
});
}
});
springboot后端controller
@PostMapping("/uploads")
public AjaxResult uploadFiles(@RequestParam("user") String user, MultipartRequest files, HttpServletRequest request) throws Exception {
try{
String filePath = RuoYiConfig.getUploadPath();
List<String> fileList = new ArrayList<>();
AtomicReference<String> errMsg = new AtomicReference<>("");
files.getMultiFileMap().forEach((key, multipartFiles) -> {
MultipartFile file = multipartFiles.get(0);
String fileName = null;
try {
fileName = FileUploadUtils.multiUpload(filePath, file, key);
fileList.add(fileName);
} catch (IOException e) {
errMsg.set(e.getMessage());
}
});
if(StringUtils.isEmpty(errMsg.get())){
return AjaxResult.success(fileList);
}
return AjaxResult.error(errMsg.get());
}catch (Exception e){
return AjaxResult.error(e.getMessage());
}
}
存储文件到服务器的核心代码:
file.transferTo("文件要存放的路径");