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

404
Views
Los archivos de carga de Strapi v4 relacionados con una entrada funcionan cuando no hay un valor inicial relacionado con el campo, pero no funcionan cuando ya hay un valor

En esencia, estoy tratando de hacer lo siguiente: https://docs.strapi.io/developer-docs/latest/plugins/upload.html#upload-files-related-to-an-entry

Mi código es ligeramente diferente, pero debería lograr el mismo objetivo de agregar el nuevo archivo como un campo a una entrada de tipo de contenido:

 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> ) }

El código anterior funciona perfectamente cuando lo uso por primera vez y subo la primera imagen que quiero agregar como valor al campo en una entrada de evento en el evento Tipo de colección. Sin embargo, si decido que ya no quiero esa imagen inicial como valor y me gustaría actualizarla, si utilizo el mismo método anterior, no funcionará.

En el tutorial que estoy siguiendo que usa quizás v3 de Strapi, pudieron actualizar/reemplazar el archivo de imagen simplemente usando el mismo código.
¿Cómo hago lo mismo para v4?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

No estoy seguro de si esta es la mejor y más alta respuesta, sin embargo, funciona al final del día. El tutorial que estoy siguiendo tal vez estaba trabajando con v3 y no tenía que eliminar la imagen para actualizarla. En mi caso para v4, no pude encontrar un código correspondiente exacto. Lo que decidí hacer fue eliminar el archivo antes de cargar el nuevo archivo de reemplazo, lo que me da el mismo resultado al final.

 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, imgId }) { 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' var uploadFormData = async () => { const res = await fetch(`${API_URL}/api/upload`, { method: 'POST', body: formData, }) if (res.ok) { console.log('res.ok') console.log('res', res) imageUploaded() } } if (imgId === null) { console.log('imgId is null') uploadFormData() } else { console.log('imgId not null') const resDelete = await fetch( `${API_URL}/api/upload/files/${imgId}`, { method: 'DELETE', // body: formData, } ) if (resDelete.ok) { console.log('resDelete.ok') console.log('resDelete', resDelete) uploadFormData() } } } 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 · Juan Pablo Isaza 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!