我遇到问题。我有docx文件存储为数据库中的字节数组。我需要得到这个文件的网址。网址应该像http://my-site.com ...但我不知道我怎么能达到它。我用内存流,文件流等阅读了许多主题,但我仍不明白我如何达到这个目标。我写在ASP MVC C#中。如何从字节数组中获取url?
回答
对于ASP.NET MVC部分,您可以使用控制器的File
方法来返回字节数组作为文件下载,就像本例中一样。
public class HomeController : Controller
{
public ActionResult Download(string id)
{
byte[] fileInBytes = GetFileDataFromDatabase(id);
return File(fileInBytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
id + ".docx");
}
private byte[] GetFileDataFromDatabase(string id)
{
// your code to access the data layer
return byteArray;
}
}
的网址是:http://.../home/download/{someId}
我应该能够执行下载后下载文件?我没有结果。 如何获取此Url? 对不起愚蠢的问题,但工作wirh文件是非常困难的。 – smile
我刚刚执行我的示例与URL(根据默认的MVC路由)http:// localhost:.../home/download/1234和浏览器提示我一个下载对话框。但这仅仅是一个示例 - 如果它不起作用,请张贴您的控制器的一些代码。 –
事情是这样的:
[HttpGet]
[Route("file/{fileId}")]
public HttpResponseMessage GetPdfInvoiceFile(string fileId)
{
var response = Request.CreateResponse();
//read from database
var fileByteArray= ReturnFile(fileId);
if (fileByteArray == null) throw new Exception("No document found");
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(new MemoryStream(fileByteArray));
response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileId+ ".docx"
};
response.Content.Headers.ContentType =
new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.Headers.Add("Content-Transfer-Encoding", "binary");
response.Content.Headers.ContentLength = fileByteArray.Length;
return response;
}
,或者如果你有一个剃刀的mvc网站只需使用FileResult:Download file of any type in Asp.Net MVC using FileResult?
这个实现是用于休息api的,现在是一个简单的解释:因为你正在从DB读取shebang,所以一旦响应离开控制器,就需要保持它可供客户端使用(保存在内存中或磁盘上以供使用由客户),更多细节:http://stackoverflow.com/questions/8156896/difference-between-memory-stream-and-filestream – SilentTremor
我不好,我用了两个内存流:),更新 – SilentTremor
- 1. 如何从字节数组中获取字节并获取数字
- 2. 如何从PictureBox获取字节数组?
- 3. 如何从JTextArea获取字节数组?
- 4. 从Cloudinary URL获取字节[]
- 5. 如何从字节数组([UInt8])获取一个字节(UInt8)?
- 6. 如何从URL中获取数字?
- 7. 如何从URL获取数组参数?
- 8. 如何从一个字节数组中获取数据
- 9. 从URL中获取前n个字节
- 10. 如何获取字节数组的TypeCode?
- 11. 如何从PDF生成的PDF中获取字节数组?
- 12. 如何在swift 3中从base64获取一个字节数组?
- 13. 如何从Spring WebClient的ClientResponse中获取最佳字节数组?
- 14. 如何从可绘制资源中获取字节数组?
- 15. 如何从c中的字节数组读取字节范围
- 16. 从字节数组中获取字节块的起始位置
- 17. 从字节数组中获取最后一个字节
- 18. 获取从字节数组字符数组,然后返回字节数组
- 19. 如何使用CFNetwork从套接字获取字节数组?
- 20. 从InputStream获取字节数组
- 21. 从ByteArrayInputStream获取内部字节数组
- 22. 从字节数组获取文件名
- 23. 获取从位图的字节数组
- 24. 从字节数组获取第0位
- 25. 从html文件获取字节数组
- 26. 获取字节数组字节元帅
- 27. 从指针数组中获取特定字节数组的大小为字节
- 28. PHP从URL获取数组
- 29. 如何从字节数组中的字节数组开始提取字节不在字节边界c#
- 30. 如何从字节数组
我想你的意思该URL在文档中?效率不是很高,但如果对字节的理解不够深入,则可以将文档转换为字符串,然后使用方法进行搜索,以了解如何使用。 http://stackoverflow.com/questions/11654562/how-convert-byte-array-to-string –