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



嗨,我正在尝试使用以下代码将任意文件与ASP.NET Core Server上传到我的ASP.NET Core Server:

        $.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() r n on microsoft.aspnetcore.http.internal.defaulthttprequest.get_get_get_get_form()

我曾经遇到过这个问题,我的解决方案是将上传机构绑定到ViewModel。这样,我就可以使用其他参数将文件上传到服务器(在您的情况下,您将传递给URL)。为此,我首先创建了一个视图模型

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

最新更新