springmvc文件下载实现
springmvc实现文件下载
使用springmvc实现文件下载有两种方式,都需要设置response的Content-Disposition为attachment;filename=test2.png
第一种可以直接向response的输出流中写入对应的文件流
第二种可以使用 ResponseEntity<byte[]>
来向前端返回文件
一、使用response
@RestController
@RequestMapping("/download")
public class DownloadController {
<span class="hljs-meta">@RequestMapping</span>(<span class="hljs-string">"/d1"</span>)
<span class="hljs-function"><span class="hljs-keyword">public</span> ResultVo<String> <span class="hljs-title">downloadFile</span><span class="hljs-params">(HttpServletResponse response)</span></span>{
String fileName=<span class="hljs-string">"test.png"</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-comment">//获取页面输出流</span>
ServletOutputStream outputStream = response.getOutputStream();
<span class="hljs-comment">//读取文件</span>
<span class="hljs-keyword">byte</span>[] bytes = FileUtils.readFileToByteArray(<span class="hljs-keyword">new</span> File(<span class="hljs-string">"D:\\my-study\\test2.png"</span>));
<span class="hljs-comment">//向输出流写文件</span>
<span class="hljs-comment">//写之前设置响应流以附件的形式打开返回值,这样可以保证前边打开文件出错时异常可以返回给前台</span>
response.setHeader(<span class="hljs-string">"Content-Disposition"</span>,<span class="hljs-string">"attachment;filename="</span>+fileName);
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
<span class="hljs-keyword">return</span> ResultVoUtil.success(<span class="hljs-string">"success"</span>);
} <span class="hljs-keyword">catch</span> (IOException e) {
<span class="hljs-keyword">return</span> ResultVoUtil.error(e);
}
}
}
推荐使用这种方式,这种方式可以以json形式给前台返回提示信息。
二、使用ResponseEntity
@Controller
@RequestMapping("/download2")
public class DownloadController2 {
<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">static</span> Logger logger= LoggerFactory.getLogger(CategoryDataController.class);
<span class="hljs-meta">@GetMapping</span>(<span class="hljs-string">"/d2"</span>)
<span class="hljs-keyword">public</span> ResponseEntity<<span class="hljs-keyword">byte</span>[]> download2(){
<span class="hljs-comment">//获取文件对象</span>
<span class="hljs-keyword">try</span> {
<span class="hljs-keyword">byte</span>[] bytes = FileUtils.readFileToByteArray(<span class="hljs-keyword">new</span> File(<span class="hljs-string">"D:\\my-study\\bill-admin\\test2.png"</span>));
HttpHeaders headers=<span class="hljs-keyword">new</span> HttpHeaders();
headers.set(<span class="hljs-string">"Content-Disposition"</span>,<span class="hljs-string">"attachment;filename=test2.png"</span>);
ResponseEntity<<span class="hljs-keyword">byte</span>[]> entity=<span class="hljs-keyword">new</span> ResponseEntity<>(bytes,headers,HttpStatus.OK);
<span class="hljs-keyword">return</span> entity;
} <span class="hljs-keyword">catch</span> (IOException e) {
logger.error(<span class="hljs-string">"下载出错:"</span>,e);
<span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
}
}
}
转载