【发布时间】:2018-02-23 14:04:53
【问题描述】:
我想模拟 API 服务器之间的传输文件。 首先,我创建了一个接收上传文件的 API。 并使用 Postman 成功上传文件。 这是要接收的代码。
[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");
}
现在,我想使用此代码从另一个 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;
}
}
如果我调用TestUpload API,它成功进入UploadFile函数。但是,当使用此代码HttpContext.Current.Request.Files.AllKeys.Any() 检查请求中是否有文件时,它会返回 false。请求中没有文件。我在这里错过了什么?
谢谢。
【问题讨论】:
-
我建议安装 Fiddler 并将成功的请求与失败的请求进行比较。
-
对不起,我不太明白如何使用 Fiddler。但我无法比较这 2 个请求,因为它像这样不同。 1) 客户端-POST FILE-> API。 2) 客户端-Get->API -POST FILE->API。第二个请求不会发布文件,但 API 会自动将文件上传到另一个 API。
标签: c# .net api file-upload webrequest