Download A File With Mvc
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)) {
Solution 1:
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');
}
Solution 2:
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;
}
Solution 3:
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();
}
Solution 4:
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
});
Post a Comment for "Download A File With Mvc"