1.前端代码:
uploadFilePromise(arr) {
let files=arr.map((value,index)=>{
return{
name:value.name,
uri:value.path
}
});
return new Promise((resolve, reject) => {
let uploadTask = uni.uploadFile({
url: url_config+'/app/common/v_uploadattachfile.do',
files:files,
// filePath: url,
// name: 'file',
// formData: {
// id: 'test'
// },
success: (res) => {
console.log("res",res)
setTimeout(() => {
resolve(JSON.parse(res.data))
}, 1000)
},
fail:(e) => {
uni.$u.toast("上传失败,请重新上传")
}
});
})
}
2.后端代码:
@RequestMapping(value = "/v_uploadfile.do", method = RequestMethod.POST)
public ReturnMsg uploadFile(HttpServletRequest request) throws Exception {
String content = "content-type";
ReturnMsg msgEntity = new ReturnMsg();
List<AttachFile> files = new ArrayList<>();
// 将请求转换成
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
/**
* 获取上传的文件列表
*/
Iterator<String> fns = mRequest.getFileNames();
while (fns.hasNext()) {
String s = fns.next();
MultipartFile mFile = mRequest.getFile(s);
if (mFile != null) {
/**
* 文件名称
*/
String originFileName = mFile.getName();
/**
* 存储目录
*/
// 会议附件存储目录
String basePath = request.getSession().getServletContext().getRealPath(Constants.FILE);
File dir = new File(basePath);
if (!dir.exists()) {
dir.mkdirs();
}
// 后缀名
String suffixName = originFileName.substring(originFileName.lastIndexOf(".") + 1);
// 随机文件名称
String randomId = Constants.createUUIDKey();
String randomName = randomId + "." + suffixName;
File file = new File(basePath + "/", randomName);
try {
if (!file.exists()) {
file.createNewFile();
}
/**
* 存储复制文件
*/
FileUtils.copyInputStreamToFile(mFile.getInputStream(), file);
/**
* 文件拷贝完成后,执行存库操作
*/
try {
AttachFile attachFile = new AttachFile();
attachFile.setAttachId(Constants.createUUIDKey());
attachFile.setAttachName(originFileName);
attachFile.setAttachPath(randomName);
attachFiles.add(attachFile);
} catch (Exception ex) {
logger.error("上传失败:" + ex);
return msgEntity.fail();
}
} catch (Exception e) {
logger.error("上传失败:" + e);
return msgEntity.fail();
}
}
}
logger.info("上传附件成功!");
return msgEntity.success(attachFiles);
}