"Incorrect Content-Type: image/png" 尝试将带有 Ajax 的 png 上传到 Asp.net 核心服务器时

"Incorrect Content-Type: image/png" when trying to upload png with Ajax to Asp.net Core server

您好,我正在尝试使用以下代码将带有 Ajax 的任意文件上传到我的 Asp.net 核心服务器:

        $.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);  
            }  
        });

其中图像来自具有 "file"

类型输入的表单

我的 C# 是:

    [ActionName("Image")]
            [HttpPost]
            [Authorize]
            public async Task<IActionResult> UploadImage(List<IFormFile> files, Guid id)
            {
                var file = Request.Form.Files[0];

问题是 "files" 是空的,"file" 给我错误 "Incorrect Content-Type: image/png"

StackTrace [string]:" 在 Microsoft.AspNetCore.Http.Features.FormFeature.ReadForm()\r\n 在 Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest.get_Form()"

我曾经遇到过这个问题,我的解决方案是将上传机制绑定到 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);  
        }  
    });