springboot输出下载txt,前端需要这么接收
时间: 2024-01-08 18:02:43 浏览: 105
springboot博客项目前后端(百度云).txt
您好,对于您的问题,您可以通过使用HttpServletResponse对象将文件以流的形式输出,并设置文件的MIME类型以及Content-Disposition响应头部,前端则可以使用a标签或者XMLHttpRequest对象进行下载。具体代码可以参考以下示例:
@RestController
public class FileDownloadController {
@GetMapping("/download")
public void downloadFile(HttpServletResponse response) throws IOException {
String filename = "file.txt";
String filepath = "/path/to/file.txt";
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
FileInputStream inputStream = new FileInputStream(filepath);
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
阅读全文