使用FileContentResult下载文件并使用JavaScript在客户端存储

7

我有一个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 文件,图片就无法打开。我检查了两个已下载的文件,它们真的不同: 我已经验证了文件可以正确打开和读取,但是我不明白为什么一旦从客户端接收后就变得混乱不堪。
3个回答

0

请尝试检查以下内容:

  1. 文件的URL是否正确,并且具有正确的扩展名

  2. 浏览器控制台中是否记录了错误。(按F12打开开发者工具>控制台)


0

使用 octet-stream 而非 octect-stream


2
从技术上讲,是的,但这会导致给出的错误吗?指出拼写错误应该在注释中完成,而不是在答案中。 - General Grievance
1
如果这确实解决了问题,你需要解释为什么。 - General Grievance

0
System.Net.Mime.MediaTypeNames.Application.Octet

为每个文件选择正确的MimeType


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接