简体   繁体   English

如何使用WebRequest发布文件

[英]How to POST file using WebRequest

I want to simulate a transfer file between API server. 我想模拟API服务器之间的传输文件。 First, I created an API that receive an uploaded a file. 首先,我创建了一个API,该API接收上传的文件。 And successfully upload a file using Postman. 并使用Postman成功上传文件。 Here is the Code to receive. 这是要接收的代码。

[AllowAnonymous]
[HttpPost]
[Route("api/data/UploadFile")]
public IHttpActionResult UploadFile()
{
    if (HttpContext.Current.Request.Files.AllKeys.Any())
    {
        var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];

        if (httpPostedFile != null)
        {
            var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/images"), "Capture1.PNG");

            httpPostedFile.SaveAs(fileSavePath);
        }
    }

    return Ok("SUCCESS");
}

I tried to upload using postman like so. 我试图像这样用邮递员上传。 邮递员上传

Now, I want to upload the file using WebRequest from another API using this code. 现在,我想使用此代码从另一个API使用WebRequest上传文件。

[AllowAnonymous]
[HttpGet]
[Route("api/data/TestUpload")]
public IHttpActionResult TestUpload()
{
    string formdataTemplate = "Content-Disposition: form-data; filename=\"{0}\";\r\nContent-Type: image/png\r\n\r\n";
    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
    byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/iisapi/api/data/UploadFile");
    request.ServicePoint.Expect100Continue = false;
    request.Method = "POST";
    request.ContentType = "multipart/form-data; boundary=" + boundary;

    string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/images"), "Capture2.PNG");

    using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
        using (Stream requestStream = request.GetRequestStream())
        {
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);
            string formitem = string.Format(formdataTemplate, "UploadedImage");
            byte[] formbytes = Encoding.UTF8.GetBytes(formitem);
            requestStream.Write(formbytes, 0, formbytes.Length);
            byte[] buffer = new byte[fileStream.Length];
            int bytesLeft = 0;

            while ((bytesLeft = fileStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                requestStream.Write(buffer, 0, bytesLeft);
            }

        }
    }

    try
    {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { }

        return Ok("SUCCESS");
    }
    catch (Exception ex)
    {
        throw;
    }
}

If I call the TestUpload API, it successfully enter the UploadFile function. 如果我调用TestUpload API,它将成功输入UploadFile函数。 But, when checking if there is files in the request using this code HttpContext.Current.Request.Files.AllKeys.Any() , it return false. 但是,使用此代码HttpContext.Current.Request.Files.AllKeys.Any()检查请求中是否有文件时,它返回false。 There is no File in the request. 请求中没有文件。 What am I missing here? 我在这里想念什么?

Thank You. 谢谢。

public virtual async Task<TResponse> PostFileAsync<TResponse>(string url, Dictionary<string, string> headers, FileResponse fileData, IProgress<ProgressCompleted> progress, CancellationToken token)
    {
        using (var request = new HttpRequestMessage(HttpMethod.Post, url))
        {
            List<byte> byteData = new List<byte>();
            Action<double> actionProgress = null;

            if (progress != null)
            {
                actionProgress = (progressValue) => progress.Report(new ProgressCompleted(progressValue));
            }
            var boundary = string.Format("----------{0:N}", Guid.NewGuid());

            var multiContent = new MultipartFormDataContent(boundary);

            foreach (var customHeader in headers)
            {
                request.Headers.Add(customHeader.Key, customHeader.Value);
            }

            var content = new ByteArrayContent(fileData.FileData);
            content.Headers.TryAddWithoutValidation("Content-Type", fileData.FileType);
            multiContent.Add(content, "file", fileData.FileName);

            request.Content = multiContent;

            using (var response = await Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false))
            {
                var total = response.Content.Headers.ContentLength.HasValue ? response.Content.Headers.ContentLength.Value : -1L;
                var canReportProgress = total != -1 && progress != null;
                if (!response.IsSuccessStatusCode)
                    RestExceptionHandlerService.Handle(response.StatusCode);

                using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                {
                    var totalRead = 0L;
                    var buffer = new byte[BufferSize];
                    var isMoreToRead = true;

                    do
                    {
                        token.ThrowIfCancellationRequested();

                        var read = await stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false);
                        if (read == 0)
                        {
                            isMoreToRead = false;
                        }
                        else
                        {
                            if (read != buffer.Length)
                            {
                                byte[] cpArray = new byte[read];
                                Array.Copy(buffer, cpArray, read);
                                byteData.AddRange(cpArray);
                            }
                            else {
                                byteData.AddRange(buffer);
                            }
                            totalRead += read;
                            if (canReportProgress)
                            {
                                progress.Report(new ProgressCompleted((double)totalRead / total * 100));
                            }
                        }
                    } while (isMoreToRead);
                }

                //TODO: server returns just string NOT Json
                return (TResponse)(object) Encoding.UTF8.GetString(byteData.ToArray(), 0, byteData.Count);
            }
        }
    }

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

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