【问题标题】:Returning a file content from Web Api using HTTP GET request [duplicate]使用 HTTP GET 请求从 Web Api 返回文件内容
【发布时间】:2017-02-25 05:26:05
【问题描述】:

客户端将向我们的 Web api 服务发出 GET 请求,我们需要使用指定的文件响应该请求。

文件内容将是字节数组,如:

byte[] fileContent = Convert.FromBase64String(retrievedAnnotation.DocumentBody);

如何将上述文件内容作为文件响应 GET 请求?

我已经删除了一个控制器:

[Route("Note({noteGuid:guid})/attachment", Name = "GetAttachment")]
[HttpGet]
public async Task<object> GetAttachment(Guid noteGuid)
{

    return new object();
}

如何将文件内容返回给 GET 请求,而不是新对象?

【问题讨论】:

    标签: c# asp.net .net rest asp.net-web-api


    【解决方案1】:

    您可以使用以下方法从 web api 返回文件内容

    public HttpResponseMessage GetAttachment(Guid noteGuid)
    {
        byte[] content = Convert.FromBase64String(retrievedAnnotation.DocumentBody);
        HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new ByteArrayContent(content);
        response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = "fileName.txt";
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
    
        return response;
    }
    

    【讨论】:

    • 非常感谢,我稍微改变了这个问题,我想知道如何在不保存本地的情况下回复附件,我只想流式传输该字节数组
    • 另外,我不知道文件类型,我只知道文件的扩展名
    • 我收到了这样的回复:{ "FileContents": "eWVz", "ContentType": "application/octet-stream", "FileDownloadName": "blabsssg4rrxt.txt" }
    • 文件下载名是正确的,但是文件内容应该只是“是”
    • 没看懂,能不能说的再清楚一点?
    猜你喜欢
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    相关资源
    最近更新 更多