[英]Download file with FileContentResult and store it client side using javascript
I've an MVC route as this:我有一个 MVC 路线是这样的:
public FileContentResult GetMedia(string media_md5)
{
// get media from DB here
processed_file_doc file_doc = getMediaFromDb(media_md5);
string filename = file_doc.Filename;
string filepath = file_doc.File_path;
byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
string fileName = filename;
FileContentResult file_result = File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
return file_result;
}
This method is called by javascript in this way:这个方法被javascript这样调用:
function DownloadMedia(row_id) {
filetable = $('#mytable').DataTable();
var data = filetable.row('#' + row_id).data();
filename = data['Filename'];
var handleSuccess = function (file) {
var a = document.createElement("a"),
file = new Blob([file], { type: "application/octect-stream" });
var url = URL.createObjectURL(file);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(function () {
document.body.removeChild(a);
window.URL.revokeObjectURL(url);
}, 0);
}
$.post("/MyController/GetMedia", { media_md5: row_id }, handleSuccess);
}
The problem is that using this code I can correctly download only.txt files, if for example I try to download a.jpg, the image can't be opened.问题是使用此代码我可以正确下载 only.txt 文件,例如,如果我尝试下载 a.jpg,则图像无法打开。 I've checked the two file downloaded and they are really different:
我检查了下载的两个文件,它们确实不同:
I've verified that the file is open and read correctly, but I can't understand why once received from client it is all messed up.我已验证该文件已打开并正确读取,但我不明白为什么一旦从客户端收到它就一团糟。
System.Net.Mime.MediaTypeNames.Application.Octet
为每个文件选择正确的 MimeType
Try checking尝试检查
The url for the file is correct with right extension文件的 url 正确,扩展名正确
Errors logged in the browser console.错误记录在浏览器控制台中。 (F12 to open developer tools > Console)
(F12打开开发者工具>控制台)
Use octet-stream instead of octect-stream使用 octet-stream 而不是 octect-stream
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.