如何使用RestSharp的AddFile()方法发送httpContext.Request.Files [0]?

时间:2019-06-27 21:39:10

标签: c# restsharp

我正在使用RestSharp调用.NET Web API。

我正在将上传的Excel文件发送到Web API。下面的代码在本地计算机上运行良好。

但是在服务器上,我们无权保存上载的文件。 我正在寻找restRequest.AddFile("content", location)接受HttpPostedFileBase postedFile = httpContext.Request.Files[0].

的替代方法
RestClient restClient = new RestClient("http://localhost:56360");
RestRequest restRequest = new RestRequest("api/excelupload/Upload");

int readWriteTimeout = restRequest.ReadWriteTimeout > 0
    ? restRequest.ReadWriteTimeout
    : ReadWriteTimeout;
    restRequest.ReadWriteTimeout = readWriteTimeout;
    restRequest.Method = Method.POST;
    restRequest.AddHeader("Content-Type", "multipart/form-data");
    restRequest.AddFile("content", location);
    restRequest.AddParameter("DetailLineNumber", "4");
    var response = restClient.Execute(restRequest);

在API上读取文件。

foreach (var content in provider.Contents)
                {
                    if (!string.IsNullOrWhiteSpace(content.Headers.ContentDisposition.FileName))
                    {
                        postedData.File = await content.ReadAsByteArrayAsync();
                    }
               }

1 个答案:

答案 0 :(得分:0)

我有一段时间没有使用RestSharp了。您可以使用流吗?像这样:

public RestRequest CreateUploadFileRequest(string path, string filename, Stream fileStream)
{
    var request = new RestRequest (Method.POST);
    request.Timeout = int.MaxValue; //test
    request.Resource = "/files/{path}";
    request.AddParameter ("path", path, ParameterType.UrlSegment);
    //Need to add the "file" parameter with the file name
    request.AddParameter ("file", filename);
    request.AddFile ("file", s => StreamUtils.CopyStream (fileStream, s), filename);

    return request;
}