java后端通过文件MultipartFile下载文件到本地
时间: 2023-11-29 18:46:14 浏览: 105
以下是Java后端通过MultipartFile下载文件到本地的示例代码:
```java
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void downloadFile(HttpServletResponse response) throws IOException {
// 获取要下载的文件
File file = new File("文件路径");
// 设置响应头
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
// 读取文件并写入响应流
InputStream inputStream = new FileInputStream(file);
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, len);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
```
在上述代码中,我们首先获取要下载的文件,然后设置响应头,包括响应类型和文件名。接着,我们读取文件并将其写入响应流中,最后刷新输出流并关闭输入输出流。
阅读全文