eneity:/** * 主鍵 */ @Id @Column(length = 50) private String id= UUIDHelper.NewID(); /** * 上傳人 */ private String siteId; /** * 文件路徑 */ private String path;
controller:
/** * 文件上傳 * @param siteId * @return RestResponse */ @ApiOperation(value = “文件上傳”, notes = “文件上傳”) @PostMapping(“/uploadFile”) public RestResponse upload(String siteId, MultipartFile file) { RestResponse restResp = new RestResponse(); if (StringUtils.isBlank(siteId)){ return restResp.setMsg(“siteId不能為空”); } try { //公共地址 String fileSpace=”F:/demo_upload”; //定義一個保存數(shù)據(jù)庫的相對目錄 String uploadPathDB=”/”+siteId+”/file”;// 獲取文件名 String filename = file.getOriginalFilename(); if(StringUtils.isNotBlank(filename)){ //確定文件的最終上傳路徑 String finalFacePath=fileSpace+uploadPathDB+”/”+filename; //設置保存數(shù)據(jù)庫中的目錄 uploadPathDB+=(“/”+filename); //判斷目錄是否存在,不存在就創(chuàng)建 File outFile=new File(finalFacePath); if(outFile.getParentFile()!=null||!outFile.getParentFile().isDirectory()){ outFile.getParentFile().mkdirs(); } //上傳 file.transferTo(outFile); //將上傳的文件名保存數(shù)據(jù)庫 DtoFileUpload files = new DtoFileUpload(); files.setSiteId(siteId); files.setPath(uploadPathDB); service.save(files); restResp.setRestStatus(StringUtil.isNull(outFile) ? ERestStatus.UNMATCH_RECORD : ERestStatus.SUCCESS); return restResp; } } catch (IOException e) { e.printStackTrace(); } return restResp.setMsg(“上傳失敗”); } /** * 文件下載 */ @ApiOperation(value = “文件下載”, notes = “文件下載”) @GetMapping(“/download”) public void download(String id, HttpServletResponse resp) throws IOException { DtoFileUpload file = service.findById(id);// String fileName=file.getSiteId(); String path=file.getPath(); String downPath=”F:/demo_upload/”+path; FileInputStream fileInputStream=new FileInputStream(downPath); ServletOutputStream outputStream = resp.getOutputStream(); IOUtils.copy(fileInputStream,outputStream); fileInputStream.close(); }