简体   繁体   中英

How do I 'attach' an image in a POST request?

Newbie here.Basically, what I'm trying to achieve is to attach an image in a client form, and then send the request to the server. Then, the server will upload to image to an S3 bucket.

Here is the code I have right now. The problem is that the server doesn't 'receive' the image. When I console.log the submitted form, it is undefined.

Client

    const [selectedFile, setSelectedFile] = useState();

  const changeHandler = (event) => {
        setSelectedFile({
      preview: URL.createObjectURL(event.target.files[0]),
      file: event.target.files[0]
    });

    };

    const handleSubmission = (e) => {
    e.preventDefault();

    const formData = new FormData();
    formData.append("file", selectedFile.file);

    
    const paramsForBucketUpload = {
      patientID: 1,
      file: formData,
      recordType: 'IMAGE',
      _contentType: selectedFile.file.type,
      fileExtension: selectedFile.file.name.split('.').pop()
    }

    Physician.uploadFileToPatientDatabase(paramsForBucketUpload);
    };

Server

  static async imageUpload(req, res) {
    console.log(req.body)
    // Some code for uploading the image
  }

The response

{
  patientID: 1,
  file: {}, // This is where the file should be, but it is empty.
  recordType: 'IMAGE',
  _contentType: 'image/jpeg',
  fileExtension: 'jpg'
}

Could anyone explain what I did wrong? Thanks.

2 things here, first you should fix your frontend (append all fields to formData) like below:

 const formData = new FormData(); formData.append("file", selectedFile.file); formData.append("patientID", 1); formData.append("recordType", 'IMAGE'); formData.append("_contentType", selectedFile.file.type); formData.append("fileExtension", selectedFile.file.name.split('.').pop()); const paramsForBucketUpload = formData

and then in your backend, you should should some file upload handler packages like multer or busboy which will help you a lot

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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