2016-09-08 45 views
0

我遇到问题。我有docx文件存储为数据库中的字节数组。我需要得到这个文件的网址。网址应该像http://my-site.com ...但我不知道我怎么能达到它。我用内存流,文件流等阅读了许多主题,但我仍不明白我如何达到这个目标。我写在ASP MVC C#中。如何从字节数组中获取url?

+0

我想你的意思该URL在文档中?效率不是很高,但如果对字节的理解不够深入,则可以将文档转换为字符串,然后使用方法进行搜索,以了解如何使用。 http://stackoverflow.com/questions/11654562/how-convert-byte-array-to-string –

回答

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}

+0

我应该能够执行下载后下载文件?我没有结果。 如何获取此Url? 对不起愚蠢的问题,但工作wirh文件是非常困难的。 – smile

+0

我刚刚执行我的示例与URL(根据默认的MVC路由)http:// localhost:.../home/download/1234和浏览器提示我一个下载对话框。但这仅仅是一个示例 - 如果它不起作用,请张贴您的控制器的一些代码。 –

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; 

    } 

,或者如果你有一个剃刀的mvc网站只需使用FileResult:Download file of any type in Asp.Net MVC using FileResult?

+0

这个实现是用于休息api的,现在是一个简单的解释:因为你正在从DB读取shebang,所以一旦响应离开控制器,就需要保持它可供客户端使用(保存在内存中或磁盘上以供使用由客户),更多细节:http://stackoverflow.com/questions/8156896/difference-between-memory-stream-and-filestream – SilentTremor

+0

我不好,我用了两个内存流:),更新 – SilentTremor