如何正确地将文件返回到视图?

问题描述 投票:0回答:1

我很难完成一项容易完成的任务,而且我不明白我是做错了什么还是我必须在其他地方寻找问题。基本上我有我的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是一个简单的字节数组,没有显示错误..

编辑我也尝试在我的'返回文件'中将内容类型设置为'application / force-download`,但没有成功。

jquery post asp.net-core-mvc asp.net-core-2.1
1个回答
0
投票

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

[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 }
}

物理路径=例如qazxsw poi

FriendlyName =例如C:\AppFiles\file.jpg

您可能需要阅读它:file.jpg

样本下载:

https://en.wikipedia.org/wiki/Media_type
© www.soinside.com 2019 - 2024. All rights reserved.