![](/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.