javascript - how to get mime type from content-type
问题描述
The thing is axios calls return files. sometimes xlsx, sometimes plain txt.
In javascript, as soon as I get them, i force download it via blob.
Something like this:
var headers = response.headers;
var blob = new Blob([response.data], {
type: headers['content-type']
});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "report.xlsx";
link.click();
As you see, I got something like this: link.download = "report.xlsx"
. What I want is to replace xlsx with dynamic mime type so that sometimes it's report.txt and sometimes it's report.xlsx.
How do I do that from content-type?
解决方案
您的应用程序的后端是什么?我在 C# (.NET Core) 中使用它来获取文件的内容类型,然后将其设置为响应中的标头:
public string GetContentType (string filePath) {
var contentTypeProvider = new FileExtensionContentTypeProvider();
string contentType;
if( !contentTypeProvider.TryGetContentType( filePath, out contentType ) ) {
contentType = "application/octet-stream";
};
return contentType;
}
编辑:修改 OP 代码以动态处理内容类型:
var headers = response.headers;
var responseType = headers['content-type'];
var fileType = "text/plain";
var fileName = "report.txt";
if ( responseType == "application/octet-stream" ) {
fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
fileName = "report.xlsx";
}
var blob = new Blob([response.data], {
type: fileType
});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = fileName;
link.click();
推荐阅读
- java - 如何在 MongoDB Java 中插入具有随机字段和固定字段的对象?
- android-studio - android studio 打不开导航文件的设计模式
- javascript - React JS useState 获取值为 true 的键
- mysql - 使用nodejs在mysql中使用三元运算符更新具有单个ENDPOINT的表单
- reactjs - 在 i18n 中设置默认语言
- python - 如何过滤具有多个布尔条件的数据框
- python-3.x - 应用程序与 buildpack 不兼容:https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz 在 heroku 服务器上部署项目
- swift - 将数据从 Alamofire 函数传递到 swift 操场中的全局变量中
- sql - 如何计算只有一种产品/所有产品的客户
- sql - 在两个日期之间搜索不返回通知的最后日期