简体   繁体   English

如何发布Web请求并从Web API响应接收文件?

[英]How to Post a web request and receive a file from web API response?

I have an Infopath Form Template on Sharepoint, I want to add a button there so when the user clicks on it, it will POST an string to the following Web API. 我在SharePoint InfoPath表单模板,我想有一个按钮添加所以当用户点击它,它会POST的字符串下面的Web API。 The following web API is tested and returns an excel file as shown: 以下Web API经过测试,并返回excel文件,如下所示:

I want to Post the FileName of the excel file using post request and it is important for me the request method to be POST type. 我想使用发布请求来发布excel文件的FileName ,这对我来说很重要,请求方法是POST类型。 and then the user will download a file with the specified 'FileName'. 然后用户将下载具有指定“文件名”的文件。 Actually i want to use post method because at the next stage i will send the content of the excel file too. 实际上,我想使用post方法,因为在下一阶段,我也将发送excel文件的内容。

Important Note : I only can use .Net FrameWork 3.5 because this is the only framework supported in InfoPath Form Templates. 重要说明 :我只能使用.Net FrameWork 3.5,因为这是InfoPath表单模板中唯一支持的框架。

[HttpPost]
public HttpResponseMessage Post([FromBody]string FileName)  
    {  
        string reqBook = "c:\somefile.xlsx";  
        //converting Excel(xlsx) file into bytes array  
        var dataBytes = File.ReadAllBytes(reqBook);  
        //adding bytes to memory stream   
        var dataStream = new MemoryStream(dataBytes);  

        HttpResponseMessage httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK);  
        httpResponseMessage.Content = new StreamContent(dataStream);  
        httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");  
        httpResponseMessage.Content.Headers.ContentDisposition.FileName = FileName;  
        httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");  

        return httpResponseMessage;  
    }  

When you perform the HttpPost on the client side, you will want to read the HttpResponseStream to get the byte data of the response stream. 在客户端执行HttpPost时,您将需要读取HttpResponseStream以获取响应流的字节数据。

Once you have the response stream data, you can then deserialize it to the type of object in C# you want, or you could alternatively just write it to the disk as 获得响应流数据后,可以将其反序列化为所需的C#对象类型,或者也可以将其写入磁盘,如下所示:

File.WriteAllBytes("someexcel.xlsx",data);

An easy way to do it would be with the HttpClient class. 一个简单的方法是使用HttpClient类。

HttpClient client = new HttpClient();
var response = client.PostAsync("", null).Result;
var content = response.Content.ReadAsByteArrayAsync().Result;
File.WriteAllBytes("excel.xlsx", content);

Just fill in the PostAsync bit with the Url and the content you wish to post. 只需在Url和您要发布的内容中填充PostAsync位即可。

I am using .Result to keep everything synchronous - but you can use 'await' if you prefer. 我正在使用.Result来使所有内容保持同步-但您可以根据需要使用'await'。

If you are working with HttpWebRequests - then the process becomes more complicated, as you need to manage the streams yourself. 如果您正在使用HttpWebRequests-则过程将变得更加复杂,因为您需要自己管理流。 The HttpClient will manage and handle it all for you - so I recommend it, unless there is something special it needs to do that it currently does not. HttpClient将为您管理和处理所有内容-因此,我建议您使用它,除非有一些特殊的事情需要执行,而当前则不需要。

Due to your .Net 3.5 requirement: 由于您的.Net 3.5要求:

private static HttpWebResponse MakeRequest(string url, string postArgument)
    {

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

        request.Method = "POST";

        request.ContentType = "multipart/form-data;";
        Stream stream = request.GetRequestStream();
        string result = string.Format("arg1={0}", postArgument);
        byte[] value = Encoding.UTF8.GetBytes(result);
        stream.Write(value, 0, value.Length);
        stream.Close();

        return (HttpWebResponse)request.GetResponse();
    }

You can then do: 然后,您可以执行以下操作:

var response = MakeRequest("http://mywebsite.com/ProcessExcel", "accounts.xlsx");

And then do 然后做

Stream objStream = response .GetResponseStream(); 
BinaryReader breader = new BinaryReader(objStream); 
byte[] data= breader.ReadBytes((int)webresponse.ContentLength); 
File.WriteAllBytes("excel.xlsx",data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM