Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

359
Views
Strapi v4: Cómo vincular un archivo cargado a un campo de una entrada en un Tipo de Colección

Tengo un tipo de colección llamado eventos. events tiene un nombre y una imagen en su arquitectura de datos. Por lo tanto, los eventos tienen un campo de nombre y un campo de imagen.

Logré cargar un archivo en strapi v4 a través del punto final /api/upload. Sé que la carga está funcionando porque el archivo que se está cargando aparece en el área de administración back-end de strapi localhost:1337 y también aparece en el backend cloudinary.

Sin embargo, el archivo de imagen no termina de agregarse al campo de imagen del evento.

He intentado seguir el código de varios ejemplos en línea, pero parece que la mayoría de los ejemplos en línea son para v3 y v4 de strapi.

En cualquier caso, debajo está mi código donde agrego ref , refId y field de formData antes de cargar el archivo ... pero aún no funciona.

 export default function ImageUpload({ evtId, imageUploaded }) { const [image, setImage] = useState(null) const handleSubmit = async (e) => { console.log('handleSubmit') e.preventDefault() const formData = new FormData() // pure javascript nothing to do with react formData.append('files', image) formData.append('ref', 'events') //'ref' The collection we want to use formData.append('refId', evtId) //'refId' The event Id formData.append('field', 'image') //'field' the image field we called 'image' const res = await fetch(`${API_URL}/api/upload`, { method: 'POST', body: formData, }) if (res.ok) { console.log('res.ok') // 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 className={styles.form}> <h1> Upload Event Image</h1> <form onSubmit={handleSubmit}> <div className={styles.file}> <input type='file' onChange={handleFileChange} /> </div> <input type='submit' value='Upload' className='btn' /> </form> </div> ) }

¿Qué estoy haciendo mal? ¿Qué debo hacer para que el archivo recién cargado se agregue al campo de imagen de la entrada de evento del tipo de colección de eventos?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Cambió la línea:

 formData.append('ref', 'events')

a

 formData.append('ref', 'api::event.event')

Y funcionó...

A continuación se muestra el código actualizado... espero que ayude a otras personas...

 import React from 'react' import { useState } from 'react' import { API_URL } from '@/config/index' import styles from '@/styles/Form.module.css' export default function ImageUpload({ evtId, imageUploaded }) { const [image, setImage] = useState(null) const handleSubmit = async (e) => { console.log('handleSubmit') e.preventDefault() const formData = new FormData() // pure javascript nothing to do with react formData.append('files', image) // formData.append('ref', 'events') //'ref' The collection we want to use formData.append('ref', 'api::event.event') formData.append('refId', evtId) //'refId' The event Id formData.append('field', 'image') //'field' the image field we called 'image' const res = await fetch(`${API_URL}/api/upload`, { method: 'POST', body: formData, }) 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 className={styles.form}> <h1> Upload Event Image</h1> <form onSubmit={handleSubmit}> <div className={styles.file}> <input type='file' onChange={handleFileChange} /> </div> <input type='submit' value='Upload' className='btn' /> </form> </div> ) }
about 4 years ago · Santiago Trujillo Report

0

hice un video que lo explica

https://www.youtube.com/watch?v=54_SKMmrJkA

Básicamente, debe cargar archivos en un formato específico o, de lo contrario, no funcionará

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!