文件上传
/** * 文件上传 * @return */ @PostMapping(value = "/upload") public String fileUpload(@RequestParam MultipartFile file) throws IOException { //获取源文件名 String originalFilename = file.getOriginalFilename(); //获取文件类型 String fileType = FileUtil.extName(originalFilename); //获取文件大小 long fileSize = file.getSize(); String uuid = splitName(originalFilename); //存储到磁盘 父目录/files/ File uploadParentFile = new File(fileUploadPath); //图片文件xxxx.png File uploadFile = new File(fileUploadPath + uuid); //判断文件是否存在然后创建一个 if(!uploadParentFile.exists()){ uploadParentFile.mkdir(); } String url = null; // 获取文件md5 String md5; file.transferTo(uploadFile); md5 = SecureUtil.md5(uploadFile); UserFile dbFiles = getFileByMd5(md5); //文件存在 if(dbFiles != null){ url = dbFiles.getFileurl(); uploadFile.delete(); } else { url = "http://localhost:9999/file/"+uuid; // 存储到数据库, UserFile saveFile = new UserFile(); saveFile.setFilename(originalFilename); saveFile.setFiletype(fileType); saveFile.setFilesize(fileSize/1024); saveFile.setFileurl(url); saveFile.setMd5(md5); fileMapper.insert(saveFile); } if(StringUtils.isEmpty(url)){ System.out.println("url is empty>>>>>>>>>>>>>>>>"); } else { System.out.println("url>>>>>>>>>>>>>>>>>>>" + url); } return url; }
文件下载
/** * 下载文件 * @param uuid * @param response */ @GetMapping(value = "/{uuid}") public void download(@PathVariable String uuid, HttpServletResponse response){ //根据文件唯一标识获取文件 File uploadFile = new File(fileUploadPath + uuid); try { //设置输出格式 ServletOutputStream os = response.getOutputStream(); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(uuid,"UTF-8")); response.setContentType("application/octet-stream"); //通过流的方式进行读取 os.write(FileUtil.readBytes(uploadFile)); os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } }
标签:文件,String,saveFile,url,上传下载,uploadFile,uuid From: https://www.cnblogs.com/qijiangforever/p/17418879.html