簡體   English   中英

如何使用spring mvc在瀏覽器中下載文件?

[英]How to download file in browser using 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();
    }
}

我沒有收到任何異常,但不確定為什么瀏覽器對話框沒有打開以下載文件。 還有它到底在哪里下載文件?

@SotiriosDelimanolis 是對的。 使用 ajax 請求無法下載文件。 只需使用'window.location'

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

我沒有足夠的信用來發表評論,所以在這里寫評論..謝謝user1298426。 我為此拼盡全力。 我正在嘗試使用 AJAX。 使用window.location.href,我可以在瀏覽器中下載文件...

我的javascript代碼如下:

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

*****:是我在控制器中的 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();
}

嘗試使用ajax下載文件是一個錯誤....

干杯......

而不是使用 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();

希望這會奏效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM