繁体   English   中英

无法在Spring MVC中下载文件

[英]Unable to download file in Spring MVC

请求映射到的我的控制器-

我将值从AJAX返回到控制器-


$.ajax({
        type: 'GET',
        dataType: 'json',
        contentType:"application/json",
        url:"/Putty/downloadProcess/?param="+param          
    });

@RequestMapping(value = "/downloadProcess", method = RequestMethod.GET)
    protected void download(@RequestParam("param") String value, HttpServletResponse response)
            throws ServletException, IOException {

        Properties prop = new Properties();
        InputStream input = new FileInputStream("config.properties");;
        prop.load(input);

        System.out.println(value);
        String path = prop.getProperty("path.MS1");
        String filepath= path.concat(value);
        System.out.println(filepath);

        File downloadFile = new File(filepath);
        FileInputStream inStream = new FileInputStream(downloadFile);


        String mimeType = "application/octet-stream";
        System.out.println("MIME type: " + mimeType);

        // modifies response
        response.setContentType(mimeType);
        response.setContentLength((int) downloadFile.length());

        // forces download
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"", downloadFile);
        response.setHeader(headerKey, headerValue);

        System.out.println(response);
        // obtains response's output stream
        OutputStream outStream = response.getOutputStream();

        byte[] buffer = new byte[4096];
        int bytesRead = -1;

        while ((bytesRead = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, bytesRead);
        }

        inStream.close();
        outStream.close();

这将在我的JSP上显示文件名


<c:forEach var="listValue" items="${files}">
        <label onClick="download('${listValue}')">${listValue}</label>
        <br>
    </c:forEach>

问题是,我可以在控制台上看到MIME类型以及AJAX返回的值-文件名。 但是,当我单击显示在我的JSP上的文件名时,没有得到“下载”对话框。 我没有正确处理请求还是缺少其他内容?

谢谢!

试试吧

ServletOutputStream out = response.getOutputStream();
response.setContentType("application/octet-stream");

   if (file.isFile())
   {
        response.setHeader("Content-Disposition", "attachment;filename=\"" + downloadFile.getName() + "\"");
        try (FileInputStream inputStream = new FileInputStream(downloadFile ))
        {
            IOUtils.copy(inputStream, out);
        }
    }

默认情况下会出现“打开/保存”对话框,因此我们不能强制执行任何操作。 这是浏览器特定的设置,您不能在客户端更改。

对于Mozilla Firefox示例: 使用Mozilla Firefox浏览器,您将获得此弹出窗口

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM