繁体   English   中英

在reactjs中使用strapi api链接上传图片和内容

[英]Link upload image with content with strapi api in reactjs

我第一次尝试在 react 中使用strapi,但我不明白如何将上传(在strapi中)图像链接到我的内容,我知道如何上传,我知道如何发布一些东西,但我不知道如何链接这个. 我阅读了很多次strapi文档,但我无法理解。

我的代码

 function ProductCreateApi({ evtId }) { const [image, setImage] = useState(null) const [posts, setPosts] = useState([]) const [updatesData, setUpdatesData] = useState({ titleproductgroup: "", }) function updateEdit(e) { const newupdate = { ...updatesData } newupdate[e.target.id] = e.target.value setUpdatesData(newupdate) console.log(newupdate) } const handleSubmit = async (e) => { console.log('handleSubmit') e.preventDefault() const formData = new FormData() formData.append('files', image) // the pic formData.append('ref', 'api::product-group.product-group') // link with my table formData.append('refId', evtId) formData.append('field', 'picproductgroup') // the row axios.post('http://localhost:1337/api/upload/', formData) e.preventDefault() const res = axios.post(`http://localhost:1337/api/product-groups/`, { "data": { titleproductgroup: updatesData.titleproductgroup } }) if (res.ok) { console.log('res.ok') console.log('res', res) // imageUploaded() } } const handleFileChange = (e) => { console.log('handleFileChange') console.log(e.target.files[0]) //this will give us an array and we want the first wone so we add 0 setImage(e.target.files[0]) } return ( <div> <h1> Upload Event Image</h1> <form onSubmit={handleSubmit}> <input onChange={(e) => updateEdit(e)} id="titleproductgroup" value={updatesData.titleproductgroup} type="text" placeholder={posts.titleproductgroup} /> <div> <input type='file' onChange={handleFileChange} /> </div> <input type='submit' value='Upload' className='btn' /> </form> </div> ) } export default ProductCreateApi

在此处输入图像描述

在评论中我写了我从属性中理解的内容

这里是我的“桌子”

谢谢你的帮助。 我希望我能提高自己谢谢你

我找到解决方案,我只是改变它

 const handleSubmit = async (e) => { console.log('handleSubmit') e.preventDefault() const formData = new FormData() formData.append('files', image) // the pic formData.append('ref', 'api::product-group.product-group') // link with my table formData.append('refId', evtId) //formData.append('field', 'picproductgroup') // the row axios.post('http://localhost:1337/api/upload/', formData).then(res => { console.log(res.data[0].id); const res2 = axios.post(`http://localhost:1337/api/product-groups/`, { "data": { titleproductgroup: updatesData.titleproductgroup, picproductgroup: res.data[0].id, } }) if (res2.ok) { console.log('res.ok') console.log('res', res2) // imageUploaded() } }).catch(error => { console.log(error.message); }); //e.preventDefault() } const handleFileChange = (e) => { console.log('handleFileChange') console.log(e.target.files[0]) //this will give us an array and we want the first wone so we add 0 setImage(e.target.files[0]) } return (

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM