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”; //定义一个保存数据库的相对目录 String uploadPathDB=”/”+siteId+”/file”;// 获取文件名 String filename = file.getOriginalFilename(); if(StringUtils.isNotBlank(filename)){ //确定文件的最终上传路径 String finalFacePath=fileSpace+uploadPathDB+”/”+filename; //设置保存数据库中的目录 uploadPathDB+=(“/”+filename); //判断目录是否存在,不存在就创建 File outFile=new File(finalFacePath); if(outFile.getParentFile()!=null||!outFile.getParentFile().isDirectory()){ outFile.getParentFile().mkdirs(); } //上传 file.transferTo(outFile); //将上传的文件名保存数据库 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(); }