admin管理员组

文章数量:1336633

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

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

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?

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

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

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?

Share edited May 21, 2014 at 7:09 Avinash R 3,1511 gold badge28 silver badges49 bronze badges asked May 21, 2014 at 6:24 user1298426user1298426 3,71715 gold badges61 silver badges116 bronze badges 6
  • so have you tried to debug it? without any concrete errors all we can do is guess what is happening. – Scary Wombat Commented May 21, 2014 at 6:29
  • 1 You cannot download a file through a javascript ajax request. – Sotirios Delimanolis Commented May 21, 2014 at 6:30
  • Are you sure that you can retrieve fileName in controller? – Wundwin Born Commented May 21, 2014 at 6:32
  • @suninsky Yes, I am getting the fileName. – user1298426 Commented May 21, 2014 at 6:35
  • @SotiriosDelimanolis why is it not possible? I am getting the file name in controller. – user1298426 Commented May 21, 2014 at 6:36
 |  Show 1 more ment

3 Answers 3

Reset to default 3

@SotiriosDelimanolis was right. File download is not possible using ajax request. Simply use 'window.location'.

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

I didn't have enough credit to give a ment so wiritting here.. Thanks user1298426. I was strugling like anything for this. I was trying with AJAX. With window.location.href, I can download file in browser...

MY javascript code is as follows:

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

*****: is the url mapping that I have in controller.

@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 plete 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 mitted"  error is very mon 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....

cheers......

Instead of using IOUtils copy method

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.

本文标签: javaHow to download file in browser using spring mvcStack Overflow