Как отправить React post requet с файловыми данными в API?
Здесь я хочу зарегистрировать пользователя с помощью изображения, поэтому я хочу передать и изображение, и имя в моих данных формы. Я могу загрузить файл, используя некоторые рекомендации (я не очень хорошо разбираюсь в react), но я не могу передать имя ввода с моими данными формы. какой процедуре следовать?
import React from 'react'
import { useState, getState } from "react";
import axios from "axios";
import { useDispatch, useSelector } from 'react-redux'
function VendorRegistration() {
const [file, setFile] = useState(null);
const UPLOAD_ENDPOINT =
"http://127.0.0.1:8000/api/orders/vendor/register/";
const handleSubmit = async e => {
e.preventDefault();
//if await is removed, console log will be called before the uploadFile() is executed completely.
//since the await is added, this will pause here then console log will be called
let res = await uploadFile(file);
console.log(res.data);
};
const userLogin = useSelector(state => state.userLogin)
const { userInfo } = userLogin
const uploadFile = async file => {
const formData = new FormData();
formData.append("avatar", file);
return await axios.post(UPLOAD_ENDPOINT, formData, {
headers: {
"content-type": "multipart/form-data",
"Authorization" : `Bearer ${userInfo.token}`,
}
});
};
const handleOnChange = e => {
console.log(e.target.files[0]);
setFile(e.target.files[0]);
};
return (
<form onSubmit={handleSubmit}>
<h1>React File Upload</h1>
<input type="file" onChange={handleOnChange} />
<input type="name" />
<button type="submit">Upload File</button>
</form>
);
}
export default VendorRegistration
Вы просто хотите привязать другой вход к state, как обычно, а затем добавить это значение к данным формы.
Я добавил элементарную валидацию, которая предотвращает нажатие кнопки отправки, если оба поля не заполнены.
import React from "react";
import axios from "axios";
const UPLOAD_ENDPOINT = "http://127.0.0.1:8000/api/orders/vendor/register/";
function VendorRegistration() {
const [file, setFile] = useState(null);
const [name, setName] = useState("");
const { userInfo } = useSelector((state) => state.userLogin);
const handleSubmit = async (event) => {
event.preventDefault();
const formData = new FormData();
formData.append("avatar", file);
formData.append("name", name);
return await axios.post(UPLOAD_ENDPOINT, formData, {
headers: {
"content-type": "multipart/form-data",
Authorization: `Bearer ${userInfo.token}`,
},
});
};
return (
<form onSubmit={handleSubmit}>
<h1>React File Upload</h1>
<input type="file" onChange={(e) => setFile(e.target.files[0])} />
<input type="text" onChange={(e) => setName(e.target.value)} value={name} />
<button type="submit" disabled={!(file && name)}>
Upload File
</button>
</form>
);
}
export default VendorRegistration;