如何从字节数组获取url

本文关键字:数组 获取 url 字节数 字节 | 更新日期: 2023-09-27 18:06:15

我有一个问题。我有docx文件存储在数据库中的字节数组。我需要得到这个文件的url。Url应该是http://my-site.com…但我不知道怎样才能到达它。我读了很多主题的记忆流,文件流等,但我仍然不明白我怎么能达到这一点。我用asp.net MVC c#编写。

如何从字节数组获取url

. 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;
    }
}

Url为:http://.../home/download/{someId}

像这样:

[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:下载任何类型的文件。. Net MVC使用FileResult?

相关文章: