首页 > 解决方案 > 如何正确地将文件返回到视图?

问题描述

我很难完成一项本应简单的任务,而且我不知道我做错了什么,或者我必须在其他地方寻找问题。基本上我有我的 javascript POST 请求:

    $.ajax(
        {
            url: "/upload",
            type: "POST",
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: function (data) {
                stopUpdatingProgressIndicator();
            }
        }
    );
}

var intervalId;

function startUpdatingProgressIndicator() {
$("#progress").show();
$.post(
    "/upload/progress",
    function (progress) {

    }
); 

在我的控制器中,我以这种方式提供文件:

return File(fileMod, System.Net.Mime.MediaTypeNames.Application.Octet, "test.mod");

但是什么也没发生,没有文件可供下载,fileMod 是一个简单的字节数组,并且没有显示错误..

编辑 我还尝试在我的“返回文件”中将内容类型设置为“应用程序/强制下载” ,但没有成功。

标签: jquerypostasp.net-core-mvcasp.net-core-2.1

解决方案


这是一个非常简单的控制器操作示例,它从数据库(路径、名称等)加载文件信息,然后从磁盘加载该文件。

[HttpGet]
public IActionResult DownloadFile(Guid fileId)
{
    var file = _context.Files.FirstOrDefault(x => x.Id == fileId);

    if (file == null)
    {
        return ...
    }

    // you may also want to check permissions logic
    // e.g if (!UserCanDownloadFiles(user)) { return ... }

    var bytes = File.ReadAllBytes(file.PhysicalPath)); // add error handling here
    return new FileContentResult(bytes, "application/octet-stream") { FileDownloadName = file.FriendlyName }
}

物理路径 = 例如C:\AppFiles\file.jpg

友好名称 = 例如file.jpg

您可能需要阅读:https ://en.wikipedia.org/wiki/Media_type

样本下载:

<a class="text-info" href="@Url.Action("DownloadFile", "MyController", new { fileId = item.Id })">Download</a>

推荐阅读