将图像与ReactJ中的strapi API链接到内容

发布于 2025-02-09 14:15:26 字数 2206 浏览 2 评论 0原文

我尝试第一次使用attrapi与react使用,我不明白如何将上传(in 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

“在此处输入映像说明”

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

,在这里我的“表”

感谢您的帮助。我希望我能改善自己

I try to use strapi for the first time with react and I can't understand how I can link upload (in strapi) image to my content, I know how upload, I know how post something but I don't know how link this. I readed a lot of times strapi documentation but I can't understand.

My code

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

enter image description here

In the comment I wrote what I understand from attributes

and here my "table"

Thanks for your help. I hope I can improve myself thanks to you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

左岸枫 2025-02-16 14:15:26

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

  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 (

I find solution, I just change that

  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 (

七禾 2025-02-16 14:15:26

我在用户名和文档上传时面临着相同的问题,然后在控制台侧给出了此错误

"Test.js:102 
POST http://localhost:1337/api/jobs-forms 400 (Bad Request)
dispatchXhrRequest @ xhr.js:258
xhr @ xhr.js:49
dispatch request @ dispatchRequest.js:51
_request @ Axios.js:170
request @ Axios.js:40
httpMethod @ Axios.js:209
wrap @ bind.js:5
handleSubmit @ Test.js:102
await in handleSubmit (async)
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
Show 22 more frames
Show less
Test.js:113 Error: AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}"

I am facing the same issues at the time userName and document upload then given this error on console side but document upload on strapi dashboard in media library

"Test.js:102 
POST http://localhost:1337/api/jobs-forms 400 (Bad Request)
dispatchXhrRequest @ xhr.js:258
xhr @ xhr.js:49
dispatch request @ dispatchRequest.js:51
_request @ Axios.js:170
request @ Axios.js:40
httpMethod @ Axios.js:209
wrap @ bind.js:5
handleSubmit @ Test.js:102
await in handleSubmit (async)
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
Show 22 more frames
Show less
Test.js:113 Error: AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}"
樱娆 2025-02-16 14:15:26

这是在React中实现的代码,其后端在Strapi中:
我已经显示了上面的错误:

function Test({ evtId }) {
  const [image, setImage] = useState(null);
  const [updatesData, setUpdatesData] = useState({
    fname: "",
  });
  const updateEdit = (e) => {
    const newUpdate = { ...updatesData };
    newUpdate[e.target.id] = e.target.value;
    setUpdatesData(newUpdate);
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('files', image);
    formData.append('ref', 'api::product-group.product-group');
    formData.append('refId', evtId);
    try {
      const uploadResponse = await axios.post('http://localhost:1337/api/upload/', formData);
      const fileId = uploadResponse.data[0].id;
      const formResponse = await axios.post('http://localhost:1337/api/jobs-forms', {
        fname: updatesData.fname,
        fileId: fileId
      });
      console.log(formResponse);
      setUpdatesData({ fname: "" });
      setImage(null);
    } catch (error) {
      console.error('Error:', error);
    }
  };
  const handleFileChange = (e) => {
    setImage(e.target.files[0]);
  };

  return (
    <div>
      <h1>Upload Event Image</h1>
      <form onSubmit={handleSubmit}>
        <input onChange={updateEdit} id="fname" value={updatesData.fname} type="text" placeholder="Enter Name" />
        <div>
          <input type='file' onChange={handleFileChange} />
        </div>
        <input type='submit' value='Upload' className='btn' />
      </form>
    </div>
  );
}
export default Test;

Here is its code which is implemented in React and its backend is in Strapi:
I have shown the error Above:

function Test({ evtId }) {
  const [image, setImage] = useState(null);
  const [updatesData, setUpdatesData] = useState({
    fname: "",
  });
  const updateEdit = (e) => {
    const newUpdate = { ...updatesData };
    newUpdate[e.target.id] = e.target.value;
    setUpdatesData(newUpdate);
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('files', image);
    formData.append('ref', 'api::product-group.product-group');
    formData.append('refId', evtId);
    try {
      const uploadResponse = await axios.post('http://localhost:1337/api/upload/', formData);
      const fileId = uploadResponse.data[0].id;
      const formResponse = await axios.post('http://localhost:1337/api/jobs-forms', {
        fname: updatesData.fname,
        fileId: fileId
      });
      console.log(formResponse);
      setUpdatesData({ fname: "" });
      setImage(null);
    } catch (error) {
      console.error('Error:', error);
    }
  };
  const handleFileChange = (e) => {
    setImage(e.target.files[0]);
  };

  return (
    <div>
      <h1>Upload Event Image</h1>
      <form onSubmit={handleSubmit}>
        <input onChange={updateEdit} id="fname" value={updatesData.fname} type="text" placeholder="Enter Name" />
        <div>
          <input type='file' onChange={handleFileChange} />
        </div>
        <input type='submit' value='Upload' className='btn' />
      </form>
    </div>
  );
}
export default Test;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文