我有一条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;
}
这种方法由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);
}
问题是使用此代码我只能正确下载.txt文件,例如,如果我尝试下载.jpg,则无法打开图像。我已经检查了下载的两个文件,它们确实不同:
我已经确认该文件已打开并正确读取,但我无法理解为什么一旦从客户端收到该文件就搞砸了。
答案 0 :(得分:0)
System.Net.Mime.MediaTypeNames.Application.Octet
为每个文件选择正确的MimeType