如何在 ASP.NET MVC 中将字节数组转换为适当的文件格式
我有一个系统,应该将提供给我的字节数组(不知道它是 pdf、txt 还是 doc)转换为可下载文件。现在通常在 ASP.NET MVC 中我会这样做。
return File(labTestResult.File, "application/pdf");
这很容易,因为我知道文件类型是什么。既然文件类型可以是任何类型,有没有办法将文件下载为其适当的格式?
I have a system that's supposed to convert a byte array (not knowing whether its pdf, txt, or doc) provided to me into a downloadable file. Now usually in ASP.NET MVC I would do it like this.
return File(labTestResult.File, "application/pdf");
That's easy because I know what the filetype is. Now that the filetype could be anything, is there a way to download the file to its appropriate format?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Asp.net MVC 具有很强的可扩展性,因此如果您需要在响应中发送任何不同的内容,您可以这样做,即您可以编写一个 ActionResult 来为您的文件提供服务,而无需指定 mime 类型,但实际上不建议这样做。
使用 这个问题从第一个字节获取mime类型。
如果您愿意,您还可以定义使用该代码的自定义操作结果,因此您的控制器代码将变为:
return AutoMimeFile(labTestResult.File);
Asp.net MVC is very extensible, so if you need to send anything differently in the response you can do so i.e. you could write an ActionResult to serve your file without specifying the mime type, but that's really not recommended.
Use the solution in this question to get the mime type from the first bytes.
If you want you can also define a custom action result that uses that code, so then your controller code becomes:
return AutoMimeFile(labTestResult.File);
我不确定是否有真正好的方法可以做到这一点。某些文件格式具有“幻数”,您可以查看此处了解更多信息关于这一点。我自己从未尝试过,所以我不能保证这样的实现有多可靠。我想最好的方法是用数据检索文件类型信息。
I'm not sure there is a really good way of doing this. Some file formats have "magic numbers" you could check for Look Here for more info on this. I've never tried this myself, so I can't vouch for how solid such an implementation would be. I suppose the best way would be to retrieve the filetype info with the data.