首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >下载二进制文件从WebApi2作为文件。服务器端

下载二进制文件从WebApi2作为文件。服务器端
EN

Stack Overflow用户
提问于 2015-08-04 16:55:30
回答 1查看 1.6K关注 0票数 1

我在这里找了几个答案,但仍然有问题。

一种是使用实体框架6将二进制byte[]保存到SQL 2014中。

我有记录的“名称”(不是文件),但我希望通过webapi2将二进制数据作为可下载的文件提供。我让它有点工作,但在浏览器上,它显示ID作为文件名,并说不能下载文件。它正在提示下载,但却无法下载。

现在,对于PoC,我很难将mime类型编码为word文档。我做错了什么,我应该如何重构这个也提供一个文件名。

我使用Office应用程序保存文档,任务窗格:

https://msdn.microsoft.com/en-us/library/office/jj715284.aspx

FileType:“压缩”=以Office (OOXML)格式将整个文档(.pptx或.docx)作为字节数组返回。

代码语言:javascript
运行
复制
Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
            function (result) {
                if (result.status === Office.AsyncResultStatus.Succeeded) {
                    vm.data.data = result.value;
                    //I call a angularJs service which post..
                   //return $http.post('https://stapi.local:8443/api/activities', vm.data);

                } else {

                }
            }
        );

然后,我尝试让用户下载以下文档。

WebAPI2控制器:

代码语言:javascript
运行
复制
[HttpGet, Route("api/activityObjectFile/{id}/{name}")]
        public HttpResponseMessage GetDataFile(int id)
        {
            var fileByte = _activityService.GetFile(id);
            HttpResponseMessage response = new HttpResponseMessage { Content = new StreamContent(new MemoryStream(fileByte))};
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/msword");
            response.Content.Headers.ContentLength = fileByte.Length;
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment filename=test.docx");

            return response;
        }

类服务库:

代码语言:javascript
运行
复制
public Byte[] GetFile(int id)
        {
            var existingActivityObjectFile = _repo.QueryAll<ActivityObject>().Where(a => a.Id == id).Select(a => a.BinaryData).First();

            return existingActivityObjectFile;
        }

客户端网址:

代码语言:javascript
运行
复制
<a href="http://stapi.local/api/activityObjectFile/14">Download</a>
EN

回答 1

Stack Overflow用户

发布于 2015-08-04 19:04:03

你现在就该这么做了:

代码语言:javascript
运行
复制
var response = new HttpResponseMessage(HttpStatusCode.OK) 
{ 
   Content = new StreamContent(new MemoryStream(fileByte))        
};
response.Content
        .Headers
        .Add("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") 
{ 
   FileName = "test.docx" 
};
return response;

至于重构的建议,您可以使用我的方法。

我有一个返回的IHttpActionResult实现,如下所示:

代码语言:javascript
运行
复制
public class DocumentAttachmentResult : IHttpActionResult {
    private readonly string fileName;
    private readonly string mimeType;
    private readonly byte[] blob;

    public DocumentAttachmentResult(string fileName, string mimeType, byte[] blob) {
        this.fileName = fileName;
        this.mimeType = mimeType;
        this.blob = blob;
    }

    private HttpResponseMessage Execute() {
        var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(new MemoryStream(this.blob)) };
        response.Content.Headers.Add("Content-Type", this.mimeType);
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = this.fileName };
        return response;
    }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) {
        return Task.FromResult(this.Execute());
    }
}

我的控制器动作看起来是这样的:

代码语言:javascript
运行
复制
    [HttpGet]
    [Route("attachments/{id:guid}/download")]
    public IHttpActionResult DownloadAttachment(Guid id) {
        var attachment = this.repository.FindById(id);
        if (attachment == null) {
            return this.NotFound();
        }
        return new DocumentAttachmentResult(attachment.Name, attachment.FileType.MimeType, attachment.BinaryBlob);
    }

我将文件名、mime类型和二进制文件存储在SQL server中,并将其建模为一个名为Attachment的实体。使用WebApi控制器上的另一个操作上载文件时,将捕获mime类型和文件。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31815080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档