简体   繁体   English

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

[英]How to download file in browser using spring mvc?

I have file on the server & that I want to download on my machine using browser.我在服务器上有文件,我想使用浏览器将其下载到我的机器上。 But I am not getting an option from browser to download the file.但是我没有从浏览器中获得下载文件的选项。

My code is我的代码是

JSP JSP

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

JS 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}
     });
};

Controller控制器

@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();
    }
}

I am not getting any exception but not sure why browser dialog is not opening to download the file.我没有收到任何异常,但不确定为什么浏览器对话框没有打开以下载文件。 Also where is it exactly downloading the file?还有它到底在哪里下载文件?

@SotiriosDelimanolis was right. @SotiriosDelimanolis 是对的。 File download is not possible using ajax request.使用 ajax 请求无法下载文件。 Simply use 'window.location' .只需使用'window.location'

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

I didn't have enough credit to give a comment so wiritting here.. Thanks user1298426.我没有足够的信用来发表评论,所以在这里写评论..谢谢user1298426。 I was strugling like anything for this.我为此拼尽全力。 I was trying with AJAX.我正在尝试使用 AJAX。 With window.location.href, I can download file in browser...使用window.location.href,我可以在浏览器中下载文件...

MY javascript code is as follows:我的javascript代码如下:

jQuery('#exportToZip').click(function() {
    window.location.href = '*****';
});

*****: is the url mapping that I have in controller. *****:是我在控制器中的 url 映射。

@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) throws ServletException, IOException {
    ServletContext context = request.getServletContext();

    // construct the complete absolute path of the file
    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();
}

Trying to download file with ajax is a blunder....尝试使用ajax下载文件是一个错误....

cheers......干杯......

Instead of using IOUtils copy method而不是使用 IOUtils 复制方法

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

You can use following :您可以使用以下内容:

 ServletOutputStream out = response.getOutputStream();

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



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

Hope this will work.希望这会奏效。

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

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