Spring框架中的文件上传和下载是常见的功能,可以通过Spring提供的MultipartFile类来实现文件上传,同时可以利用ServletOutputStream来实现文件下载。下面看看代码如何使用。
文件上传:
@Controller
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
// 处理文件上传逻辑
return "uploadSuccess";
}
}
文件下载:
@Controller
public class FileDownloadController {
@GetMapping("/download")
public void handleFileDownload(HttpServletResponse response) {
// 设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"example.txt\"");
try {
// 从服务器读取文件内容并写入到响应流
ServletOutputStream outputStream = response.getOutputStream();
// 这里可以从文件系统或者数据库中读取文件内容
outputStream.write("File content".getBytes());
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
原文链接: https://blog.csdn.net/2401_82884096/article/details/137906929