我在项目中使用 webapi 进行文件上传。我正在用邮递员进行测试。但是,Request.Content.IsMimeMultipartContent() 始终返回 false。
邮递员截图:
文件上传控制器代码:
public async Task<HttpResponseMessage> UserImageUpload()
{
try
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var userImageUploadPath = HttpContext.Current.Server.MapPath(CommonParameters.UserProfileImageServerPath);
var streamProvider = new CustomMultipartFormDataStreamProvider(userImageUploadPath);
await Request.Content.ReadAsMultipartAsync(streamProvider);
var files = new List<string>();
foreach (MultipartFileData file in streamProvider.FileData)
{
files.Add(Path.GetFileName(file.LocalFileName));
}
return Request.CreateResponse(HttpStatusCode.OK, files);
}
catch (Exception exception)
{
logger.ErrorFormat("An error occured in UserImageUpload() Method - Class:FileUploadController - Message:{0}", exception);
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
这是邮递员错误。尝试删除 Content-Type 标头。当发送实际的帖子时,浏览器将自动添加适当的标题并创建边界。
Postman 中的标头中无需提及 Content-Type,我尝试发送不带 Content-Type 的附件,这对我来说效果很好。 当我使用
Content-Type: multipart/formdata
时,它会抛出一个错误,提示“无法得到任何响应”。邮递员也使用 Content-Type →text/plain; charset=utf-8
发送您的文件附件。