如何使用spring mvc在浏览器中下载文件?

时间:2014-05-21 06:24:43

标签: java javascript spring-mvc

我在服务器上有文件&我想使用浏览器在我的机器上下载。但我没有从浏览器中获取下载文件的选项。

我的代码是

JSP

<div id="jqgrid">
    <table id="grid"></table>
    <div id="pager"></div>
</div>

JS

jq("#grid").jqGrid({
    ....

    onCellSelect: function(rowid, index, contents, event) {
    ...
       var fileName = jQuery("#grid").jqGrid('getCell',rowid,'fileName');
       $scope.downloadFile(fileName);
    }
});


$scope.downloadFile = function(fileName) {
    $http({
        url: "logreport/downLoadFile", 
        method: "GET",
        params: {"fileName": fileName}
     });
};

控制器

@RequestMapping(value = "/downLoadFile", method = RequestMethod.GET)
public void downLoadFile(HttpServletRequest request, HttpServletResponse response) {
    try {
        String fileName = request.getParameter("fileName");
        File file = new File(filePath +"//"+fileName);
        InputStream in = new BufferedInputStream(new FileInputStream(file));

        response.setContentType("application/xlsx");
        response.setHeader("Content-Disposition", "attachment; filename="+fileName+".xlsx"); 


        ServletOutputStream out = response.getOutputStream();
        IOUtils.copy(in, out);
        response.flushBuffer();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

我没有得到任何异常但不确定为什么浏览器对话框没有打开以下载文件。它还在哪里下载文件?

3 个答案:

答案 0 :(得分:3)

@SotiriosDelimanolis是对的。使用ajax请求无法进行文件下载。 只需使用'window.location'

$scope.downloadFile = function(fileName) {
    window.location.href = 'logreport/downLoadFile?fileName=asdad1';
};

答案 1 :(得分:1)

我没有足够的功劳来发表评论,所以在这里很好..感谢user1298426。我为此喜欢什么。我正在尝试使用AJAX。使用window.location.href,我可以在浏览器中下载文件...

我的javascript代码如下:

jQuery('#exportToZip').click(function(){

          window.location.href = '*****';
      });

*****:是我在控制器中的网址映射。

@RequestMapping(value = "/****")
@ResponseBody
public void downloadRequesthandler(HttpServletRequest request,HttpServletResponse response) {
    String status;
    try {
        filedownloader.doGet(request, response); 

    } catch (ServletException e) {
        status="servlet Exception occured";
        e.printStackTrace();
    } catch (IOException e) {
        status="IO Exception occured";
        e.printStackTrace();
    }
    //return status;
}

public void doGet(HttpServletRequest request,HttpServletResponse response)抛出ServletException,IOException {      ServletContext context = request.getServletContext();             //构造文件的完整绝对路径

        File downloadFile = new File(filePath);
        System.out.println("downloadFile path: "+ filePath);
        FileInputStream inputStream = new FileInputStream(downloadFile);

     // get MIME type of the file
        String mimeType = context.getMimeType(fullPath);
        if (mimeType == null) {
            // set to binary type if MIME mapping not found
            mimeType = "application/octet-stream";
        }
        System.out.println("MIME type: " + mimeType);

        response.setContentLength((int) downloadFile.length());

        // set headers for the response
        String headerKey = "Content-Disposition";
        String headerValue = String.format("attachment; filename=\"%s\"",downloadFile.getName());
        response.setHeader(headerKey, headerValue);


        OutputStream outStream = response.getOutputStream();

        byte[] buffer = new byte[BUFFER_SIZE];
        System.out.println("buffer: "+ buffer.length);
        int bytesRead = -1;

        // write bytes read from the input stream into the output stream
      //be carefull in this step. "writebeyondcontentlength" and "response already committed"  error is very common here 
        while ((bytesRead = inputStream.read(buffer))!=-1  ) {

            outStream.write(buffer, 0, bytesRead);
        }

        inputStream.close();
        outStream.close();
        }

尝试使用ajax下载文件是一个错误....

欢呼声......

答案 2 :(得分:0)

而不是使用IOUtils复制方法

ServletOutputStream out = response.getOutputStream();
IOUtils.copy(in, out);

您可以使用以下内容:

 ServletOutputStream out = response.getOutputStream();

 byte[] bytes = IOUtils.toByteArray(in);
 out.write(bytes);



 out.close();
 out.flush();

希望这会奏效。