一、背景
移动端项目使用uniapp开发,项目有上传附件的需求。现在分享给大家,一起进步
二、前端
关键代码:
uni.chooseFile({
type: "all",
count: this.count,
success: res => {
let len = 0;
res.tempFiles.forEach((item, index) => {
len++;
let info = {
filename: item.name,
filepath: item.path,
filetype: this.fileHz(item.name),
file: item
}
let flag = /\.(doc|docx|xls|xlsx|ppt|pdf|zip|rar|jpg|png|jpeg)$/
.test(
item.name.toLowerCase())
//双重保证
if (this.size <= info.file.size) {
this.$toast("文件最大不超过2M");
return
}
if (flag) {
this.upload(material, info, index1);
} else {
this.$toast("请选择.doc、.docx、.xls、.xlsx、.ppt、.pdf、.zip、.rar格式文件")
return
}
})
},
fail: err => {
console.log(err);
}
});
/* 截取后缀名 */
fileHz(name) {
//获取最后一个.的位置
var index = name.lastIndexOf(".");
//获取后缀
var ext = name.substr(index + 1);
return ext
},
发送请求接口:
upload(material, info, index) {
const formData = new FormData();
if (!info) {
this.$toast('请上传文件');
return;
}
formData.append('file', info.file);
let para = {
//这是额外的参数
}
formData.append("para", JSON.stringify(para));
uni.uploadFile({
url: 'htpp:127.0.0.1:8080/xxx/xxxx/xxxxx', //仅为示例,非真实的接口地址
filePath: info.file.path,
name: 'file',
formData: {
para: JSON.stringify(para)
},
success: (uploadFileRes) => {
this.$toast("上传成功");
},
fail: (err) => {
this.$toast("提交失败:" + err);
},
},
三、后端
关键代码:
java
public void uploadMaterial(HttpServletRequest request, HttpServletResponse response, JSONObject parado) throws Exception {
response.setContentType("text/html;charset=UTF-8");
JSONObject result = new JSONObject();
try {
// 处理入参
JSONObject para = JSONObject.parseJSON(parado.getString("para"));
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
CommonsMultipartFile file = (CommonsMultipartFile) multipartRequest.getFile("file");
if(file != null){
InputStream stream = file.getInputStream();
String filename = file.getOriginalFilename();
String filetype = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
byte[] b= IoUtil.getBytes(stream);
String base64 = Base64Encoder.encode(b);
para.put("base64",base64);
para.put("wjmc",filename);
para.put("type",filetype);
}
} catch (BusinessException e) {
logger.error("上传材料失败", e);
} catch (Exception e) {
logger.error("上传材料失败", e);
}
......
}