我有问题。我将docx文件存储为数据库中的bytes数组。我需要获取此文件的URL。网址应该像http://my-site.com ...但我不知道我怎么能达到它。我通过内存流,文件流等阅读了很多主题,但我仍然不了解如何实现这一目标。我在ASP MVC C#中写作。
答案 0 :(得分:3)
对于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}
答案 1 :(得分:1)
这样的事情:
[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;
}
或者如果您有Razor Mvc网站,只需使用FileResult:Download file of any type in Asp.Net MVC using FileResult?