微软的Web API返回的文件?使用字节[]? [英] Microsoft Web Api return a file? use byte[]?

查看:227
本文介绍了微软的Web API返回的文件?使用字节[]?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用的ASP.NET Web API。我希望能够从API下载用C#PDF文件(该API生成)。

我可以只具备API返回一个byte []?并为C#应用程序可我只是做:

 字节[] = PDF client.DownloadData(urlToAPI);?

  File.WriteAllBytes()?


解决方案

更好的与StreamContent返回的Htt presponseMessage它里面。

下面是例子:

 公开的Htt presponseMessage的GetFile(字符串ID)
{
    如果(String.IsNullOrEmpty(ID))
        返回Request.CreateResponse(的HTTPStatus code.BadRequest);    字符串文件名;
    串localFilePath;
    INT档案大小;    localFilePath = getFileFromID(ID,出的文件,出档案大小);    HTT presponseMessage响应=新HTT presponseMessage(的HTTPStatus code.OK);
    response.Content =新StreamContent(新的FileStream(localFilePath,FileMode.Open,FileAccess.Read));
    response.Content.Headers.ContentDisposition =新System.Net.Http.Headers.ContentDispositionHeaderValue(附件);
    response.Content.Headers.ContentDisposition.FileName =文件名;
    response.Content.Headers.ContentType =新MediaTypeHeaderValue(应用程序/ PDF格式);    返回响应;
}

UPD 帕特里奇评论:
如果任何人来到这里找送出去,从一个字节数组,而不是实际文件的回应,你会代替StreamContent想用新的ByteArrayContent(someData)(请参阅here).

I want to use ASP.NET Web API. I want to be able to download a PDF with C# from the API(that the API generates).

Can I just have the API return a byte[]? and for the c# application can I just do:

byte[] pdf = client.DownloadData("urlToAPI");? 

and

File.WriteAllBytes()?

解决方案

Better to return HttpResponseMessage with StreamContent inside of it.

Here is example:

public HttpResponseMessage GetFile(string id)
{
    if (String.IsNullOrEmpty(id))
        return Request.CreateResponse(HttpStatusCode.BadRequest);

    string fileName;
    string localFilePath;
    int fileSize;

    localFilePath = getFileFromID(id, out fileName, out fileSize);

    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = fileName;
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

    return response;
}

UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).

这篇关于微软的Web API返回的文件?使用字节[]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆