【问题标题】:Upload base64 image to the server with Axios and React native使用 Axios 和 React Native 将 base64 图像上传到服务器
【发布时间】:2019-05-01 12:45:46
【问题描述】:

实际上我们有网站使用 dropzone.js 将图像上传到服务器。

我正在使用 react 本机应用程序,需要复制 dropzone js 行为。

我正在尝试发送 base64 图像但请求返回 Multipart requests must contain at least one part.

 saveImages(images) {
    let config = {
        headers: {
            'Content-Type': 'multipart/form-data',
            'X-Requested-With': 'XMLHttpRequest'
        }
    };
    images.forEach(img => {
        let imgFormData = `data:${img.mime};base64,${(img.data)}`;
        let blob = this.dataURItoBlob(imgFormData);
        let formData = new FormData(document.forms[0]);
        formData.append('file', blob);
        axios.post(SAVE_IMAGE_URL, formData, config)
            .then(res => console.log(res))
            .catch(err => {
                console.log(err);
                console.log(err.status);
                console.log(err.code);
            })
    });
}

    dataURItoBlob = (dataURI) => {

        let byteString;
        if (dataURI.split(',')[0].indexOf('base64') >= 0)
            byteString = atob(dataURI.split(',')[1]);
        else
            byteString = unescape(dataURI.split(',')[1]);

        let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];


        let ia = new Uint8Array(byteString.length);
        for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }

        return new Blob([ia], {type:mimeString});
}

【问题讨论】:

    标签: asp.net reactjs react-native axios dropzone.js


    【解决方案1】:

    用 react-native-fetch-blob 包修复

        images.forEach(img => {
            RNFetchBlob.fetch('POST', SAVE_IMAGE_URL, {
                'Content-Type': 'multipart/form-data'
            }, [
                // element with property `filename` will be transformed into `file` in form data
                {name: 'file', filename: 'file.png', data: img.data}
            ]).then((resp) => {
                console.log(resp);
                // ...
            }).catch((err) => {
                // ...
            })
    
        })
    

    【讨论】:

      猜你喜欢
      • 2019-10-27
      • 2019-03-20
      • 2021-12-31
      • 1970-01-01
      • 2023-02-13
      • 2021-09-28
      • 1970-01-01
      • 2021-05-29
      • 2018-12-05
      相关资源
      最近更新 更多