简体   繁体   中英

Download File By jquery from java

i Have a problem with download file by jquery.

I have a post function that send request in the java code.

I return the file but this doesn't download.

Input

        <input type="button" id="export-csv" value="Export result in CSV"/>

Html-jquery Code

$( "#export-csv" ).click(function(  ) {

        var request=$.ajax({
            method: "POST",
            url: 'user/writeCsv',
            data: $( "#search-form" ).serialize(),
            dataType: "text/csv"
        }).done(function(data) {
            window.location.href = (data);
        });   


//      $.post( "user/writeCsvToReturn", $( "#search-form" ).serialize())
    });

Java code

@RequestMapping(value="/user/writeCsv",method=RequestMethod.POST)
    public FileWriter writeCSVFile(HttpServletResponse   response,ServerSearchCommand ssc, Model model, BindingResult result) throws IOException {

FileWriter fileWriter= new FileWriter("/tmp/searchcsv.csv");
fileWriter.flush();

    //WRITE DATA FILE 


    fileWriter.close();
    return fileWriter;
}

If you don't want to submit form , you can have this work around write the file in response object in get request:-

@RequestMapping(value="/user/writeCsv",method=RequestMethod.Get)
public void writeCSVFile(HttpServletResponse   response,ServerSearchCommand ssc, Model model, BindingResult result) throws IOException {

OutputStream outStream = response.getOutputStream();
 // Write data to this outStream
 outStream.close();
} 

On front end , side append file to iFrame and make iFrame stye = display:none :-

    var url = contextPath + "/user/writeCsv";
   var hiddenIFrameID = 'frameid',
    iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
        iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;

Simply you cannot. With Ajax you cannot download a file due to security reasons. All you can do is a submit a form request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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