繁体   English   中英

.NET Core Web API中的IFormFile对于axios和ajax文件上载为空,但在Postman中有效

[英]IFormFile in .NET Core Web API is null for axios and ajax file upload but works in Postman

介绍

所以我有一个API,它将使用以下签名将文件上传到Azure:

public async Task<IActionResult> Post([FromForm]IEnumerable<IFormFile> files)

此API是使用Postman构建和测试的,可以与以下参数配合使用:

邮递员API

但是,当我尝试在我的react应用程序中使用Postman或axios生成的AJAX jQuery调用它时,IFormFile文件变量为null。

handleFileChange = async (event) => {
    let formData = new FormData();
    let files = event.target.files[0];
    formData.append('file', logo); // Can put "files" here or the imported picture "logo"


 console.log("Form Data:", formData.get("files"));
    await axios.post('api/files/uploadfiles', formData,{
        'content-type': "multipart/form-data",
        'Content-Type': "multipart/form-data",
    })
         .then(response => response.data)
        .then(data => console.log("File Upload Response:" , data));
}

.NET Core通过axios / ajax获取的API请求

在此处输入图片说明

.NET Core与Postman一起获得的API请求

在此处输入图片说明 您将在此处注意到,主要区别在于邮递员在文件下有文件,而axios请求似乎仅在“结果视图”下引用了文件,而在文件下则没有内容。 我要在表格上附加正确的项目吗? 我已经尝试使用导入的图像以及来自以下输入字段的动态图像进行此操作:

<FormGroup id = 'file-form'>
    <Label for="file">Attach Files:</Label>
    <Input type="file" name="files" id="File" onChange={this.handleFileChange}/>
</FormGroup>

但没有运气。 任何帮助将不胜感激!


更新#1

复习了一些Microsoft 文档之后,我发现Microsoft 文档中有一个警告,说将表单的enctype改为“ multipart / form-data”。 我试图这样做无济于事。

这是我在action方法中做到的:

[HttpPost]
public void Post([FromForm]ValueFile files)
{
     //do logic
}

然后创建一个名为ValueFile的ViewModel

public class ValueFile
{
    public IEnumerable<IFormFile> Files { get; set; }
}

在我的Web客户端中,我使用了jQuery ajax:

$('#fileTest').on('change',
        function() {

            var fd = new FormData();
            fd.append('files', $('#fileTest')[0].files[0]);

            $.ajax({
                "async": true,
                "crossDomain": true,
                "url": "http://localhost:5000/api/values",
                "method": "POST",
                "processData": false,
                "contentType": false,
                "mimeType": "multipart/form-data",
                "data": fd
            }).done(function (response) {
                console.log(response);
            });
        });

<form id='file-form'>
    <Label for="file">Attach Files:</Label>
    <Input type="file" name="files" id="fileTest"  />
</form>

希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM