Reactjs 通过React to API发送图像
我们与一位朋友一起创建了一个CRUD应用程序,它在前端使用React和Laravel作为API。我们希望将从应用程序发送图像添加到API中,但不幸的是,经过5个小时的尝试、观看YouTube教程和阅读博客教程后,我们只能使用Postman发送图像。字幕和数字发送正确 API控制器Reactjs 通过React to API发送图像,reactjs,laravel,image,rest,Reactjs,Laravel,Image,Rest,我们与一位朋友一起创建了一个CRUD应用程序,它在前端使用React和Laravel作为API。我们希望将从应用程序发送图像添加到API中,但不幸的是,经过5个小时的尝试、观看YouTube教程和阅读博客教程后,我们只能使用Postman发送图像。字幕和数字发送正确 API控制器 您应该发送带有值multipart/form data的HTTP头内容类型: await axios.post("http://192.168.5.90/api/backeries",{ nam
您应该发送带有值multipart/form data的HTTP头内容类型:
await axios.post("http://192.168.5.90/api/backeries",{
name: addForm.
price: addForm.
image: addForm.image
}, {
headers: { "Content-Type": "multipart/form-data" }
})
此外,你想发送的名称和价格对吗?是的,它的工作
import axios from 'axios';
import React from 'react';
import './AddProduct.css';
function Add(props){
const imageRef = React.useRef()
const [addForm, setAddForm] = React.useState({
name: '',
price: '',
image: null
})
const submit = async event => {
event.preventDefault();
try{
let formdata = new FormData()
formdata.append('image', addForm.image);
await axios.post("http://192.168.5.90/api/backeries",{
name: addForm.name,
price: addForm.price,
image: addForm.image
})
console.log("Dane wysłane!");
console.log(addForm.image)
console.log(formdata)
} catch(ex){
console.log(ex.response);
}
}
return(
<div className="add-transparent">
<div className="edit">
<h1 className="add-cancel" onClick={props.toggleShowAdd}>X</h1>
<div className="add-form">
<h1 className="add-title"> Dodawanie produktu </h1>
<form onSubmit={submit} encType='multipart/form-data' method="POST">
<input
type="text"
className="add-input"
placeholder="Nazwa"
name="name"
value={addForm.name}
onChange={e => setAddForm({...addForm, name: e.target.value})}
/>
<input
type="number"
step="0.01"
className="add-input"
placeholder="Cena"
name="price"
value={addForm.price}
onChange={e => setAddForm({...addForm, price: e.target.value})}
/>
<input
type="file"
className="add-input"
name="image"
ref={imageRef}
onChange={e => setAddForm({...addForm, image: e.target.files[0]})}
/>
<button
type="submit"
className="add-btn"
>Zapisz</button>
</form>
</div>
</div>
</div>
)
}
export default Add;
await axios.post("http://192.168.5.90/api/backeries",{
name: addForm.
price: addForm.
image: addForm.image
}, {
headers: { "Content-Type": "multipart/form-data" }
})