Sim*_*ons 4 .net c# file-upload asp.net-web-api postman
我正在关注此博客文章以使用 C# Web API 上传图像。
这篇文章解释了如何使用 ARC 来做到这一点,并且效果很好。
但是当我尝试使用 POSTMAN 做同样的事情时,它失败了。
这是我的请求快照。
哼! 这太棘手了。除了Content-Type在工具中明确设置标题之外,您所做的一切都是正确的。你不能那样做。每当您在工具form-data的Body选项卡中附加文件时,邮递员都会自动检测Content-Type并在您的发布请求中发送它。
设置Content-Type为“multipart/form-data”涉及设置多个部分的边界的复杂概念,详见此处。因此,Content-Type明确设置标头会弄乱请求。邮递员工具会自动为您完成设置边界的繁重工作,这就是为什么它不希望您content-type在这种情况下明确设置边界。请查看我Authorization在系统上上传图像文件时如何仅设置标题:
Authorization如果您的 Web 服务器上没有任何身份验证,您甚至可能不需要此标头。因此Headers,您的情况下的有效选项卡应该只是空的,即根本没有键值对。
注意:仅供参考,multipart/form-data即使您不需要在工具中明确设置图像文件的正确内容类型。
在帖子中,您引用的数据正在上传为“x-www-form-url-encoded”
您的邮递员屏幕截图显示您正在将其作为“表单数据”上传
此外,您还添加了一个密钥“image01”,而 ARC 示例似乎并未发送密钥。
如果您想使用表单数据上传文件,则需要采用不同的方法:
// POST api/files
public async Task<HttpResponseMessage> Post()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
string value;
try
{
// Read the form data and return an async data.
var result = await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the form data.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
// return multiple value from FormData
if (key == "value")
value = val;
}
}
if (result.FileData.Any())
{
// This illustrates how to get the file names for uploaded files.
foreach (var file in result.FileData)
{
FileInfo fileInfo = new FileInfo(file.LocalFileName);
if (fileInfo.Exists)
{
//do somthing with file
}
}
}
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, value);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = files.Id }));
return response;
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4311 次 |
| 最近记录: |