import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.util.UUID; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import dao.upAnddownDao; import po.Sdownload; @RestController @RequestMapping("/test") public class textController { @Autowired private upAnddownDao uad; // 上传 @PostMapping("/upload") // 必须要有MultipartFile类型参数。而且参数名必须与表单file控件名一致 public String upload(MultipartFile file) { // 上传图片存储目录 String path = "d:/upload"; // 获取文件名并使用UUID生成新文件名 System.out.println(file); String fileName = file.getOriginalFilename(); System.out.println(fileName); System.out.println(fileName.substring(fileName.lastIndexOf("."))); String newFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf(".")); // 在指定上传图片存储目录中创建新文件 File targetFile = new File(path, newFileName); // 如果找不到指定目录和文件,就新创建此目录和文件 if (!targetFile.exists()) { targetFile.mkdirs(); } // 将文件写入硬盘(myFile在内存中) try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } Sdownload dl = new Sdownload(); String url = path + "/" + newFileName; System.out.println(url); dl.setUrl(url); dl.setDeltag(0); Integer result = uad.upload(dl); System.out.println(result); return "ok"; } // 下载 @RequestMapping(value = "/down", method = RequestMethod.GET) public ResponseEntity<InputStreamResource> downfile(Integer dlid) throws IOException { System.out.println(dlid); Sdownload sdl = uad.download(dlid); String url = sdl.getUrl(); // 明确要读取的文件 File file = new File(url); FileSystemResource fsr = new FileSystemResource(file); // 设置响应输出流的头部信息 HttpHeaders hh = new HttpHeaders(); String fname = URLEncoder.encode(file.getName(), "utf-8"); System.out.println(fname); hh.add("Content-Disposition", "attachment;filename=\"" + fname + "\""); hh.add("Cache-Control", "no-cache, no-store, must-revalidate"); hh.add("Pragma", "no-cache"); hh.add("Expires", "0"); // 完成响应输出 return ResponseEntity.ok().headers(hh).contentLength(fsr.contentLength()) .contentType(MediaType.parseMediaType("application/octet-stream;charset=utf-8")) .body(new InputStreamResource(fsr.getInputStream())); } }
标签:springboot,url,System,springframework,file,org,println,import,中存 From: https://www.cnblogs.com/liweimingbk/p/17086966.html