SpringMVC实现点击自动下载文件

业务场景:点击一个链接进行下载文件,浏览器自动下载。不是在线打开。

/**
 * 点击下载文件使用
 *
 * @param response
 * @param fileName
 * @param request
 * @throws IOException
 */
@RequestMapping(value = "/batch/dl", method = RequestMethod.GET)
@ResponseBody
public void testDownload(HttpServletResponse response, String fileName, HttpServletRequest request) throws IOException {
   //根据文件名称获取服务器上的文件
    File downloadFile = new File(fileName);
    ServletContext context = request.getServletContext();
    String mimeType = context.getMimeType(fileName);
    if (mimeType == null) {
        mimeType = "application/octet-stream; charset=ISO8859-1";
        System.out.println("context getMimeType is null");
    }
    response.setContentType(mimeType);
    response.setContentLength((int) downloadFile.length());
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"",
            new String(downloadFile.getName().getBytes("ISO8859-1")));
    response.setHeader(headerKey, headerValue);
    try {
        InputStream myStream = new FileInputStream(fileName);
        //装载文件
        OutputStream outputStream = response.getOutputStream();
        IOUtils.copy(myStream, outputStream);
        response.setCharacterEncoding("utf-8");
        response.flushBuffer();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
本站的文章多是老王开发工作中问题的记录,一个字一个字敲的,切实可行,可以分享,需要留个原文链接,至少也意思意思吧!
vsalw技术博客 » SpringMVC实现点击自动下载文件

你想下载这个主题吗?

沟通一下 扯会蛋