Download a File by Jquery.Ajax

Download a file by jQuery.Ajax

2019 modern browsers update

This is the approach I'd now recommend with a few caveats:

  • A relatively modern browser is required
  • If the file is expected to be very large you should likely do something similar to the original approach (iframe and cookie) because some of the below operations could likely consume system memory at least as large as the file being downloaded and/or other interesting CPU side effects.

fetch('https://jsonplaceholder.typicode.com/todos/1')

.then(resp => resp.blob())

.then(blob => {

const url = window.URL.createObjectURL(blob);

const a = document.createElement('a');

a.style.display = 'none';

a.href = url;

// the filename you want

a.download = 'todo-1.json';

document.body.appendChild(a);

a.click();

window.URL.revokeObjectURL(url);

alert('your file has downloaded!'); // or you know, something with better UX...

})

.catch(() => alert('oh no!'));

download file using an ajax request

Update April 27, 2015

Up and coming to the HTML5 scene is the download attribute. It's supported in Firefox and Chrome, and soon to come to IE11. Depending on your needs, you could use it instead of an AJAX request (or using window.location) so long as the file you want to download is on the same origin as your site.

You could always make the AJAX request/window.location a fallback by using some JavaScript to test if download is supported and if not, switching it to call window.location.

Original answer

You can't have an AJAX request open the download prompt since you physically have to navigate to the file to prompt for download. Instead, you could use a success function to navigate to download.php. This will open the download prompt but won't change the current page.

$.ajax({
url: 'download.php',
type: 'POST',
success: function() {
window.location = 'download.php';
}
});

Even though this answers the question, it's better to just use window.location and avoid the AJAX request entirely.

Handle file download from ajax post

Create a form, use the POST method, submit the form - there's no need for an iframe. When the server page responds to the request, write a response header for the mime type of the file, and it will present a download dialog - I've done this a number of times.

You want content-type of application/download - just search for how to provide a download for whatever language you're using.

File download through ajax

Don't make an AJAX call, but rather set the window's href to point to URL for downloading the file. Then change the content type of the response to application/x-download and set the header of the response to be Content-disposition:

response.setContentType("application/x-download");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
response.flushBuffer();

function download(fileName) {
window.location.href = "/download?description=test&logId=123";
}

Also, have a look at this SO post which addresses a similar problem to the one you have.

How to use JQuery to Download a File or Use Ajax to Display Error Page

You can try returning an additional flag along with your response.

    public async Task<IActionResult> Index(int FileID)

{

try

{

string filePath = await _myService.GetFilePath(FileID);

return Json (new { status = "valid" , file = Url.Action("Download", new {FilePath = filepath})});

}

catch (MyCustomException ex)

{

return Json(new { status = "Invalid", pv = PartialView("MyErrorPage", new MyErrorViewModel(ex)) });

}

}



public async Task<IActionResult> Download(string FilePath )

{

string tempFilePath = System.IO.Path.Combine(_hostingEnvironment.WebRootPath, "FILE-DIR", FilePath);

byte[] fileBytes = await System.IO.File.ReadAllBytesAsync(tempFilePath);



//Clean up the temp file

return file = File(fileBytes, "MIME-TYPE", "FILE-NAME");

}

How to download a file through ajax request in asp.net MVC 4

Please, try this in ajax success

success: function () {
window.location = '@Url.Action("DownloadAttachment", "PostDetail")';
}

Updated answer:

public ActionResult DownloadAttachment(int studentId)
{
// Find user by passed id
// Student student = db.Students.FirstOrDefault(s => s.Id == studentId);

var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == studentId);

byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath);

return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);

}

Ajax request:

$(function () {
$("#DownloadAttachment").click(function () {
$.ajax(
{
url: '@Url.Action("DownloadAttachment", "PostDetail")',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
data: {
studentId: 123
},
type: "GET",
success: function () {
window.location = '@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })';
}
});

});
});

Using jQuery AJAX to download a binary file

Just use XHR directly. This example is taken from MDN:

var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.png", true);
oReq.responseType = "arraybuffer";

oReq.onload = function(oEvent) {
var arrayBuffer = oReq.response;

// if you want to access the bytes:
var byteArray = new Uint8Array(arrayBuffer);
// ...

// If you want to use the image in your DOM:
var blob = new Blob([arrayBuffer], {type: "image/png"});
var url = URL.createObjectURL(blob);
someImageElement.src = url;

// whatever...
};

oReq.send();

Download file by ajax success

You can do this:
1) add a empty a href tag in form:

<a id="download-broshura" name="download-file" download> </a>

2) in controller change url path to file:

$result['file'] = $file;

3) add this to your ajax function:

document.getElementById('download-broshura').click();

this will simulate a click and the file will be automatic download



Related Topics



Leave a reply



Submit