1.后端java代碼:
/** * 圖片上傳 * @param request * @return * @throws Exception */ @PostMapping("/upload") public AjaxResult uploadFile(HttpServletRequest request) throws Exception { try { // 上傳文件路徑 String filePath = RuoYiConfig.getUploadPath(); 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()); } }
2.前端代碼:
uni.chooseImage({ count: 1, sizeType: ['original', 'compressed'], sourceType: ['camera', 'album'], //這要注意,camera調拍照,album是打開手機相冊 success: (res) => { // 頁面展示 that.image1 = res.tempFilePaths[0]; uni.uploadFile({ url: 'http://localhost:8081/app/upload', //post請求的地址 filePath: res.tempFilePaths[0], name: 'file', formData: {}, header: { Authorization: that.authtoken }, success: (myres) => { console.log(myres); var jsonObject = JSON.parse(myres.data); if (jsonObject.code == 200) { var imageUrl = jsonObject.data.url; // 后端存儲url that.resultForm.subManSign = imageUrl; } } }) } });
以上;