POST Ant设计使用axios上传文件到django ImageField

mklgxw1f  于 2022-11-26  发布在  Go
关注(0)|答案(2)|浏览(135)

我如何将Ant Design Upload文件发送到我的Django后端模型ImageField中。我正在使用axios来使用PUT方法更新用户配置文件。此时我将我的图像设置为状态并访问文件对象以将其发送到我的后端。然而,这引发了404错误。我是否应该在发布之前以某种方式更改我的文件数据?或者这里可能有什么问题?
我发布的文件:

state = {
    file: null,
};
    
handleImageChange(file) {
        this.setState({
          file: file
        })
        console.log(file)
    };

handleFormSubmit = (event) => {
        const name = event.target.elements.name.value;
        const email = event.target.elements.email.value;
        const location = event.target.elements.location.value;
        const image = this.state.file;
        const sport = this.state.sport;
        axios.defaults.headers = {
            "Content-Type": "application/json",
            Authorization: this.props.token
        }
        const profileID = this.props.token
        axios.patch(`http://127.0.0.1:8000/api/profile/${profileID}/update`, {
            name: name,
            email: email,
            location: location,
            sport: sport,
            image: image,
            })
            .then(res => console.log(res))
            .catch(error => console.err(error));
        }

当我console.log(file)时,我可以正确地看到我上传的文件,但我认为发送它会导致错误

ih99xse1

ih99xse11#

尝试将“内容类型”更改为"Content-Type" : "multipart/form-data"

0vvn1miw

0vvn1miw2#

Ant Design(版本4.X)可执行的示例。

const formData = new FormData();    
const [file, setFile] = useState(null);    
const authConfig = {
        headers: {
            'Authorization': `Token ${userTokens.access}`,
            'Accept': 'application/json',
            'Content-Type': 'multipart/form-data',
        }
    }

const handleUpload = async () => {
   
    await axios.post('/upload-employees/', formData, authConfig)
        .then(() => {
            setFile([]);
            message.success('upload successfully.');
        })
        .catch(error => {
            console.log(error);
            message.error('upload failed.');
        })
};

const props = {
    beforeUpload: (file) => {
        console.log(file);
        setFileCSV(file);
        return false;
    },
};

useEffect(() => {
    if (file) {
        formData.append('file_name_atr_here', file);
    }
}, [file])

此代码的JSX

<>
    <Upload {...props} maxCount={1}>
        <Button>Select File</Button>
    </Upload>

    <Button
        name={'file_name_atr_here'}
        onClick={handleUpload}
        disabled={!file}
    >
        Start Upload
    </Button>
</>

相关问题