单张上传
前端:
methods: {
takePhoto() {
const self = this
// 从相册选择6张图
uni.chooseImage({
count: 6,
sizeType: ['original', 'compressed'],
// sourceType: ['album'],
success: function(res) {
console.log(res.tempFiles[0])
uni.uploadFile({
url: 'http://192.168.2.106:9888/qt/tq/uploadFile', //仅为示例,非真实的接口地址
// header: {
// "Content-Type": "multipart/form-data"
// },
filePath: res.tempFilePaths[0],
name: 'file',
formData: {
},
success: (uploadFileRes) => {
console.log(uploadFileRes.data);
}
});
}
});
}
}
后端:
@AnonymousAccess // 忽略身份验证的注解
@ApiOperation(value = "测试app上传图片", notes = "测试app上传图片", httpMethod = "POST")
// @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "地区id")})
@RequestMapping("/uploadFile")
public ReturnJson uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
System.out.println(file);
String str = "\\";
String substring = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(str) + 1);
//判断文件是否存在 如果已经存在,先删除
File temp = new File("D:\\pic\\" + substring);
if (temp.exists()) {
temp.delete();
}
//将文件写入到指定路径
FileOutputStream out = new FileOutputStream("D:\\pic\\" + substring);
out.write(file.getBytes());
out.flush();
out.close();
return null;
}
多张上传:
多端开发时,考虑官方文档说明,小程序不支持多传,所以多端考虑,循环实现多张上传:
methods: {
takePhoto() {
const self = this
// 从相册选择6张图
uni.chooseImage({
count: 6,
sizeType: ['original', 'compressed'],
// sourceType: ['album'],
success: function(res) {
self.urls = res.tempFilePaths;
for (var i = 0; i < res.tempFilePaths.length; i++) {
console.log(res.tempFilePaths[i])
uni.uploadFile({
url: 'http://192.168.2.106:9888/qt/tq/uploadFile', //仅为示例,非真实的接口地址
// header: {
// "Content-Type": "multipart/form-data"
// },
filePath: res.tempFilePaths[i],
name: 'file',
formData: {
},
success: (uploadFileRes) => {
console.log(uploadFileRes.data);
}
});
}
}
});
}
}