admin管理员组

文章数量:1202004

I am attempting to submit an image using server action (useActionState) and I encounter the following error: "Error: exceeded 2mb limit." This only arises in following scenario: upload image -> action returns with error (validation failed, etc.) -> upload image again to submit. After submitting the image in a row, I get the exceeded limit error, even though the image is less than 2MB. However, if I follow this sequence: submit image -> get error from action -> upload empty image -> upload image again, error does not occur.

actions.js:

export async function shareMeal(prevState, formData) {
  console.log(formData.get('image'));
 

  return {
    message: 'Please upload an image.',
    payload: formData, // Reset image
  }
}

page.js

   <form className={classes.form} action={formAction}>
     <ImagePicker label='Image' name='image'/>
     <button> submit </button>
   </form>

ImagePicker:

export default function ImagePicker({ label, name }) {
  const imageRef = useRef()
  const [pickedImage, setPickedImage] = useState()

  function handleButtonClick() {
    imageRef.current.click()
  }

  function handleImageChange(event) {
    const file = event.target.files[0]

    if (!file) {
      setPickedImage(null)
      return
    }
    const reader = new FileReader()

    reader.onload = function () {
      setPickedImage(reader.result)
    }

    reader.readAsDataURL(file)
  }

  return (
    <div className={classes.picker}>
      <label htmlFor={name}>{label}</label>
      <div className={classes.controls}>
        <div className={classes.preview}>
          {!pickedImage && <p>No image picked yet.</p>}
          {pickedImage && <Image src={pickedImage} alt='Picked image' fill />}
        </div>

        <input
          className={classes.input}
          type='file'
          name={name}
          accept='image/png, image/jpeg'
          id={name}
          ref={imageRef}
          onChange={handleImageChange}
        />
        <button
          className={classes.button}
          type='button'
          onClick={handleButtonClick}
        >
          Pick an Image
        </button>
      </div>
    </div>
  )
}

if i increase the limit to 4mb then it works without any problem. i can upload and submit images 3-4 times in a row.

EDIT: after some investigation i've found that the error is caused by returning FormData inside payload.

Edit2: as a workaround i'm returning an object that contains all the field instead of formData:

 const meal = {
    title: formData.get('title'),
    summary: formData.get('summary'),
    instructions: formData.get('instructions'),
    image: formData.get('image'),
    creator: formData.get('name'),
    creator_email: formData.get('email'),
  }

this seems to have fixed the bug, not sure if my approach is correct

本文标签: