jquery - 如何正确地将文件返回到视图?
问题描述
我很难完成一项本应简单的任务,而且我不知道我做错了什么,或者我必须在其他地方寻找问题。基本上我有我的 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 是一个简单的字节数组,并且没有显示错误..
编辑 我还尝试在我的“返回文件”中将内容类型设置为“应用程序/强制下载” ,但没有成功。
解决方案
这是一个非常简单的控制器操作示例,它从数据库(路径、名称等)加载文件信息,然后从磁盘加载该文件。
[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>
推荐阅读
- laravel - 基于角色特定能力的 Laravel 角色和权限
- python - 如何从python中的数据框中仅过滤特定日期?
- javascript - 仅使用 javascript 添加指向伪元素的链接
- php - DBUnit 与 PHPUnit 不兼容?
- iis - 更新在 iis 中发布的 Web 应用程序时出现 404 错误
- c++ - 错误 LNK2019:函数中引用了未解析的外部符号 __imp_get_driver_instance
- wordpress - 从分类 CPT UI 获取自定义字段 ACF
- bash - 可选地在 bash 脚本中传递参数
- unity3d - 避免光线投射在没有图层蒙版的情况下击中播放器
- node.js - Workload Identity 经常抛出“尝试检索访问令牌时返回了一个禁止的错误...”错误