▶SpringBoot集成文件 - 基础的文件上传和下载 | Java 全栈知识体系
1.文件上传
@RestController
@RequestMapping("/file")
public class upload {
@PostMapping("/upload")
public String upload(@RequestParam(value = "file", required = true) MultipartFile file) {
try {
// 本地文件保存位置
String uploadPath = "E:\\upload"; // 改这里
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
System.out.println(uploadDir.getAbsolutePath());
// 本地文件
File localFile = new File(uploadPath + File.separator + file.getOriginalFilename());
// transfer to local
file.transferTo(localFile);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return "sucessfully";
}
}
file.transferTo(localFile)方法的作用是将文件从源位置传输到本地目标文件中。
file.transferTo()方法是MultipartFile接口的默认实现,它会使用IO流的方式将上传的文件保存到指定的本地文件。因此,您不需要进行额外的IO流操作。
@RestController
@RequestMapping("/file")
public class upload {
@PostMapping("/upload")
public String upload(@RequestParam(value = "file", required = true) MultipartFile file) {
try {
String uploadPath = "E:\\upload";
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
System.out.println(uploadDir.getAbsolutePath());
// 本地文件
File localFile = new File(uploadPath + File.separator + file.getOriginalFilename());
try (InputStream inputStream = file.getInputStream();
OutputStream outputStream = new FileOutputStream(localFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
return "sucessfully";
}
}
2.文件下载
@GetMapping("/download")
public void download(HttpServletResponse response) {
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition",
"attachment;filename=file_" + System.currentTimeMillis() + ".hprof");
// 从文件读到servlet response输出流中
File file = new File("/Users/pdai/pdai_heap_dump_test.hprof"); // 改这里
try (FileInputStream inputStream &