Java后端读取的文件如何传输给前端请使用springmvc举例
在SpringMVC中,可以使用org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody接口将Java后端读取的文件传输给前端。
示例代码如下:
@RequestMapping(value = "/download", method = RequestMethod.GET)
public StreamingResponseBody downloadFile(HttpServletResponse response) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=myfile.txt");
// 读取文件内容
String filePath = "/path/to/myfile.txt";
InputStream inputStream = null;
try {
inputStream = new FileInputStream(new File(filePath));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
final InputStream finalInputStream = inputStream;
return outputStream -> {
int nRead;
byte[] data = new byte[1024];
while ((nRead = finalInputStream.read(data, 0, data.length)) != -1) {
outputStream.write(data, 0, nRead);
}
finalInputStream.close();
};
}
在上述代码中,首先设置响应的Content-Type和Content-Disposition,然后读取要下载的文件内容并创建一个InputStream对象。接着,创建一个实现org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody接口的匿名内部类,实现writeTo方法,将读取的文件内容写入输出流中。最后返回这个匿名内部类的实例即可。
原文地址: https://www.cveoy.top/t/topic/Mxe 著作权归作者所有。请勿转载和采集!