上傳檔案到物理路徑並下載
阿新 • • 發佈:2019-01-11
上傳檔案到物理路徑並下載
-
上傳檔案到伺服器物理路徑,以便下載使用
介面如下:
/** * * @TODO: 小程式上傳單個檔案到伺服器 * @param request * @param file 檔案 * @throws IOException * @return(展示方法引數和返回值) */ @ResponseBody @RequestMapping("/fileUpload") public String fileUpload(@RequestParam("file") MultipartFile file){ Map<String, Object> res = new HashMap<String, Object>(); String fileName = UUID.randomUUID().toString().replaceAll("-", "") + getSuffix(file); // 判斷是否有檔案 if (StringUtils.isNotBlank(fileName)) { String uploaddir= "d:/upload/"; File upload = new File(uploaddir); if(!upload.exists()) { upload.mkdirs(); } File fileinfo=new File(String.format("%s%s", uploaddir, fileName)); try { FileUtils.writeByteArrayToFile(fileinfo, file.getBytes()); } catch (IOException e) { e.printStackTrace(); } res.put("fileName", fileName); } res.put("success", "success"); String json = JSON.toJSONString(res); return json; }
該介面實現的是檔案上傳到指定路徑(“d:/upload/”)下,並返回生成的檔名用於下載
-
下載物理路徑中的圖片
/** * * @TODO: 下載圖片 * @param fileId * @return(展示方法引數和返回值) */ @ResponseBody @RequestMapping("/getImg") public BaseResponse getFile(@RequestParam("fileId") String fileId) { //檔案上傳到伺服器之後,檔案路徑儲存到資料庫中,在這裡獲取路徑以便下載使用 String imgUrl = testService.selectImgUrlById(fileId); String filePath = "d:/upload/" + imgUrl; String imgBase64 = WechatDownload.downloadCheckEquipmentImg(filePath); return BaseResponseUtil.success("data:image/png;base64," + imgBase64); }