【问题标题】:How get url from bytes array? [closed]如何从字节数组中获取 url? [关闭]
【发布时间】:2017-01-16 08:35:13
【问题描述】:

我有问题。我将 docx 文件作为字节数组存储在数据库中。我需要得到这个文件的 url。网址应该像 http://my-site.com... 但我不知道我怎么能到达它。我阅读了许多有关 memorystream、filestream 等的主题,但我仍然不明白如何才能达到这一点。我用 ASP MVC C# 编写。

【问题讨论】:

  • 我认为您的意思是 URL 在文档中?效率不是很高,但是如果您对字节不太了解,您可以将文档转换为字符串,然后使用您知道如何使用的方法进行搜索。 stackoverflow.com/questions/11654562/…

标签: c# asp.net asp.net-mvc


【解决方案1】:

对于 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}

【讨论】:

  • 执行下载后我应该能够下载文件吗?我没有结果。如何获取此网址?很抱歉提出愚蠢的问题,但处理 wirh 文件对我来说非常困难。
  • 我刚刚使用 url(根据默认 MVC 路由)localhost:.../home/download/1234 执行了我的示例,浏览器提示我一个下载对话框。但这只是一个示例 - 如果它不起作用,请发布您的控制器的一些代码。
【解决方案2】:

类似这样的:

[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?

【讨论】:

  • 这个实现是为了一个rest api,现在简单的解释:因为你正在从数据库中读取shebang,所以一旦响应离开控制器,你需要让它对客户端可用(将它保存在内存中或在客户端使用的磁盘上),更多详细信息:stackoverflow.com/questions/8156896/…
  • 我的错,我用了两个内存流:),更新了
猜你喜欢
  • 1970-01-01
  • 2019-12-13
  • 2013-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-08
相关资源
最近更新 更多