【问题标题】:file upload from reactjs not working. POST call for file upload from reactjs not working从 reactjs 上传文件不起作用。从reactjs上传文件的POST调用不起作用
【发布时间】:2018-04-18 23:10:30
【问题描述】:

以下是我的文件上传代码。

<form encType="multipart/form-data" action="">
    <input type="file" name="fileName" defaultValue="fileName"></input>
    <input type="button" value="upload" onClick={this.handleClick.bind(this)}></input>
</form>


handleClick(){
            let deliveryId = this.props.params.deliveryId;
            var data = new FormData();
            var imagedata = document.querySelector('input[type="file"]').files[0];
            data.append("data", imagedata);
            console.log('Data', data);

            fetch(apiBaseUrl, {
                mode: 'no-cors',
                method: "POST",
                body: JSON.stringify({
                    'item_file': data,
                    'delivery_id': deliveryId,
                    'description': 'test description'
                })
            }).then(function (res) {
                if (res.ok) {
                    alert("Perfect! ");
                } else if (res.status == 401) {
                    alert("Oops! ");
                }
            }, function (e) {
                alert("Error submitting form!");
            });
        }

虽然,我可以在 'imagedata' 中看到文件详细信息,但 'data' 是空的。我无法弄清楚为什么“数据”是空的。这就是后端调用失败的原因。

以下是提交后到服务器的请求载荷:

{item_file: {}, delivery_id: "eeb9422e-9805-48eb-a8be-ad2e27f3f643", description: "测试描述"}

【问题讨论】:

    标签: html reactjs file-upload multipartform-data


    【解决方案1】:

    您可以使用FormData本身来实现文件上传,并带有deliveryId等额外参数。而且你不能对文件进行字符串化。

     handleClick() {
        let deliveryId = this.props.params.deliveryId;
        var imagedata = document.querySelector('input[type="file"]').files[0];
    
        var data = new FormData();
        data.append("item_file", imagedata);
        data.append('delivery_id', deliveryId);
        data.append('description', 'test description');
    
        fetch(apiBaseUrl, {
            mode: 'no-cors',
            method: "POST",
            body: data
        }).then(function (res) {
            if (res.ok) {
                alert("Perfect! ");
            } else if (res.status == 401) {
                alert("Oops! ");
            }
        }, function (e) {
            alert("Error submitting form!");
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-08-03
      • 2010-12-27
      • 1970-01-01
      • 2014-01-09
      • 1970-01-01
      • 1970-01-01
      • 2013-03-17
      • 2013-12-09
      相关资源
      最近更新 更多