最近在做uniapp相關的開發,在上傳圖片的時候遇到了一些問題,所幸經過一些努力,解決開發過程中遇到的困難,記錄一下uniapp上傳圖片的實現過程
1、前端代碼
setPic1: function() {
var me = this;
var serverUrl = this.serverUrl;
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
success: function(res) {
const tempFilePaths = res.tempFilePaths[0];
uni.uploadFile({
url: serverUrl+ '/api/common/upload',
filePath: tempFilePaths,
name: 'file',
success: (myres) => {
var jsonObject = JSON.parse(myres.data);
if(jsonObject.code == 0){
var imageUrl = jsonObject.data.url;
me.businessLicencesUrl = imageUrl;
me.isUploadimg = true;
}
}
});
}
});
},
uploadFile中URL指向的是自己的上傳接口, filePath就是一個臨時路徑
2、java的後端代碼
@ApiOperation("圖片上傳")
@PostMapping("/common/upload")
public AjaxResult uploadFile(HttpServletRequest request) throws Exception
{
try
{
// 上傳文件路徑
String filePath = IMAGEHOME;
MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
//對應前端的upload的name參數"file"
MultipartFile file = req.getFile("file");
// 上傳並返回新文件名稱
String fileName = FileUploadUtils.upload(filePath, file);
String url = serverConfig.getUrl() + fileName;
Map<String, Object> result = new HashMap<>();
result.put("fileName", fileName);
result.put("url", url);
return AjaxResult.success(result);
}
catch (Exception e)
{
return AjaxResult.error(e.getMessage());
}
}
測試圖片上傳的功能,最後真機測試,或是通過小程序測試,PC端調試的時候,uniapp生成的臨時文件路徑可能會有問題,至此圖片上傳功能完成