Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从WebApi2下载二进制文件作为文件。服务器端_C#_Asp.net_Entity Framework 6_Asp.net Web Api2_Binaryfiles - Fatal编程技术网

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

C# 从WebApi2下载二进制文件作为文件。服务器端,c#,asp.net,entity-framework-6,asp.net-web-api2,binaryfiles,C#,Asp.net,Entity Framework 6,Asp.net Web Api2,Binaryfiles,我在这里找到了几个答案,但仍然有一个问题。 一个系统正在使用Entity Framework 6将二进制字节[]保存到SQL 2014中 我有记录的“名称”(不是文件),但我想通过webapi2将二进制数据作为可下载文件提供。我有一些工作,但在浏览器上显示的ID作为文件名,并说不能下载文件。它会提示您下载,但无法下载 现在对于PoC,我正在将mime类型硬编码为word文档。我做错了什么?我应该如何重构它以同时提供一个文件名 我正在使用Office应用程序保存文档,任务窗格: FileType

我在这里找到了几个答案,但仍然有一个问题。
一个系统正在使用Entity Framework 6将二进制字节[]保存到SQL 2014中

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

现在对于PoC,我正在将mime类型硬编码为word文档。我做错了什么?我应该如何重构它以同时提供一个文件名

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

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

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控制器:

[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;
        }
public Byte[] GetFile(int id)
        {
            var existingActivityObjectFile = _repo.QueryAll<ActivityObject>().Where(a => a.Id == id).Select(a => a.BinaryData).First();

            return existingActivityObjectFile;
        }
<a href="http://stapi.local/api/activityObjectFile/14">Download</a>
班级服务库:

[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;
        }
public Byte[] GetFile(int id)
        {
            var existingActivityObjectFile = _repo.QueryAll<ActivityObject>().Where(a => a.Id == id).Select(a => a.BinaryData).First();

            return existingActivityObjectFile;
        }
<a href="http://stapi.local/api/activityObjectFile/14">Download</a>
public Byte[]GetFile(int-id)
{
var existingActivityObjectFile=\u repo.QueryAll

这应该可以让你马上开始:

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
的实现,它如下所示:

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());
    }
}
    [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中,并将其建模为一个名为
附件的实体。
当我使用WebApi控制器上的另一个操作上载文件时,会捕获mime类型和文件。

我尝试过,但似乎遇到了相同的问题。浏览器希望保存文件“14”这是我发送的ID,当我尝试在IE下载管理器中保存时,它显示“无法下载此文件”@Mastro您正在使用哪个版本的IE?在内容处理标题中,您在附件后缺少分号,它应该是
附件;filename=test.docx
在这台计算机上,它正在Microsoft Edge(Windows 10)计算机上弹出。让我试试我的Windows 8(IE)机器。好的,我在我的另一台机器上试过了,IE崩溃了。也许这与我保存它的方式有关。我使用的是Word.File类型“compressed”保存二进制数据。我假设它是您拥有的Open XML minetype。我现在使用的是Anish Patel的代码。不过,同样的问题是,我认为它与字节[]有关可能是数据。使用上述客户端Url,文件将始终采用您的最终Url段的名称。出于测试目的,您是否可以尝试在
/activityObjectFile/14
之后添加任意文件名,例如:
activityObjectFile/14/test.docx
。您的WebAPI2控制器似乎具有接受文件名的路由设置这是路线的一部分,但您似乎没有利用它。