javascript - 使用 Axios 将表单数据发布到 .NET API

标签 javascript .net asp.net-mvc reactjs axios

我正在使用 React 和 Axios 将 formData 发布到内部 .NET API。

API 需要这样的数据:

    [HttpPost("upload")]
    public virtual async Task<IActionResult> PostMulti(Int64 parentId, ICollection<IFormFile> fileData)
    {
        foreach (var file in fileData) {
            await SaveFile(file, parent);
        }

        return Created("", Map(Repository.Get(parentId)));
    }

当我单步执行调试器时,“fileData”的计数始终为 0。

这是我使用 Axios 发送它的方式:

    const formData = new FormData();
    formData.append('image', this.state.file);

    console.log("this.state.file = ", this.state.file);
    console.log("formData = ", formData);

    axios({
        url: `/api/gameMethods/playerStates/${this.props.playerId}/files/upload`,
        method: 'POST',
        data: formData,
        headers: {
            Accept: 'application/json',
            'Content-Type': 'multipart/form-data'
        }
    })
       .then((response) => {
            //handle success
            console.log('response -- then: ', response);
            this.setState({
                file: this.state.file
            });
        })
        .catch((response) => {
            //handle error
            console.log('response -- catch: ', response);
        }); 

我使用 console.log 进行调试。当我写出来时,它会显示文件对象(名称、大小等)。

它还在方法的“.then”处理程序中触发并显示:

"response -- then: data: Array(0), status: 201, statusText: "Created" "

所以,我不知道为什么它没有向 API 发送任何内容,我也不知道发生了什么或如何解决这个问题。

如有任何帮助,我们将不胜感激。

谢谢!

最佳答案

您应该发布 formData 的数组

const filesToSubmit = []
filesToSubmit.push((new FormData()).append('image', this.state.file))

并且在发布数据时,属性名称应该是 formData

axios({
    url: `/api/gameMethods/playerStates/${this.props.playerId}/files/upload`,
    method: 'POST',
    data: {formData : filesToSubmit},
    headers: {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data'
    }
})

如果构建数组时出现问题,您需要将 IFormFile 属性添加到数组

关于javascript - 使用 Axios 将表单数据发布到 .NET API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50451025/

相关文章:

javascript - 从框架中弹出音乐播放器

c# - Response.StatusCode 在 nunit 测试中为 null

c# - 如何找到调用当前方法的方法?

c# - 具有多个参数的 Web Api 2 通用传递方法

.net - 获取 "Cannot implicitly convert type ' 表 [ ]' to ' Generic.List<>'

javascript - 显示来自 json 结果类型的图像数据

javascript - 在 asp.net mvc 应用程序中动态更改样式

javascript - jQuery 方法,可选参数的顺序

javascript - 如何在数据表中使用Rowspan

javascript - 对于严重依赖某些外部 JS 库的应用程序,有哪些好的做法可以使用?