![](/img/trans.png)
[英]InvalidOperationException: Incorrect Content-Type: ASP.NET Core
[英]“Incorrect Content-Type: image/png” when trying to upload png with Ajax to Asp.net Core server
嗨,我正尝试使用以下代码将带有Ajax的任意文件上传到我的Asp.net Core服务器:
$.ajax({
url: '/Provider/Image/' + guid,
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: image,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
图像来自表单,其中输入类型为“文件”
我的C#是:
[ActionName("Image")]
[HttpPost]
[Authorize]
public async Task<IActionResult> UploadImage(List<IFormFile> files, Guid id)
{
var file = Request.Form.Files[0];
问题是“文件”为空,“文件”给我错误“错误的内容类型:image / png”
StackTrace [string]:“ Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm(),Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest.get_Form()的r \\ n”
我曾经遇到过这个问题,我的解决方案是将上传机制绑定到ViewModel。 这样,我就可以将带有其他参数的文件上传到服务器(在您的情况下,就是您要传递给url的guid)。 为此,我首先创建了一个视图模型
public class UploadImageViewModel
{
public IFormFile file {get;set;}
public Guid uniqueId {get;set;}
}
并在我的控制器中使用了
public async Task<IActionResult> UploadImage(UploadImageViewModel model)
{
//Here I can access my file and my Guid
var file = model.file;
Guid id = model.uniqueId;
}
然后在我的jquery调用中,我传递了一个模型而不是一个(或多个)文件:
var dataModel = new FormData();
dataModel.append('file', document.getElementById("YOUR-FILEUPLOAD-FIELD-ID").files[0]);
dataModel.append('uniqueId', guid);
$.ajax({
url: '/Provider/Image/' + guid,
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: image,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.