Reputation: 3
I need to allow the user on my site to download a file (xml File)
I tried
public FileResult DownloadFile(string fileid)
{
if (!string.IsNullOrEmpty(fileid))
{
byte[] fileBytes = Encoding.ASCII.GetBytes(FileData);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet,FileName + ".bccx");
}
return null;
}
ajax:
function downloadFile(id) {
$.ajax({
url: sitePath + "Controller/DownloadFile?fileid=" + id,
type: 'post',
asysnc: false
})
.done(function () {
});
}
but nothing is downloaded
Upvotes: 0
Views: 11669
Reputation: 494
it is very simple
make link
<a href="/Home/preview?id=Chrysanthemum.jpg" > Download File</a>
and your controller
public ActionResult preview(string id)
{
string Filename = Path.GetFileName(@id);
string location = id;
try
{
if (System.IO.File.Exists(location))
{
FileStream F = new FileStream(@location, FileMode.Open, FileAccess.Read, FileShare.Read);
return File(F, "application/octet-stream", Filename);
}
}
catch (IOException ex)
{
}
return View();
}
Upvotes: 1
Reputation: 572
You can't use ajax post to download a file. It cannot save files directly into user's machine. The ajax post would get the response in raw format but it won't be a file.
Just use
function downloadFile(id) {
window.location = "/Controller/DownloadFile?fileid=" + id;
}
Upvotes: 1
Reputation: 732
Does it have to be done using ajax? Maybe you could open another window with the file generation address and let the browser do the job:
function downloadFile(id) {
window.open(sitePath + "Controller/DownloadFile?fileid=" + id, '_blank');
}
Upvotes: 2
Reputation: 13
Here is a way I accomplish downloading, hope that helps.
$.ajax({
url: sitePath + "Controller/DownloadFile?fileid=" + id,
type: 'GET',
success: function (filename) { //I return the filename in from the controller
frame = document.createElement("iframe");
frame.id = "iframe";
frame.style.display = 'none';
frame.src = '/FileDirectory?fileName=' + filename; //the path to the file
document.body.appendChild(frame);
},
cache: false,
contentType: false,
processData: false
});
Upvotes: 0