Home > Blockchain >  upload image with Multer not from Form
upload image with Multer not from Form

Time:10-02

I have an image URL in my code and i want to save it as a FormData with multer.

i tried 2 ways for save image with multer.

number1 perfectly works but number2 dosent work. i think the problem is in the "part 2"

number 1 (works)

my function to save image from form

 const onChangeUploadImage = (e) => {
    //-----------------------------------------------part 1---------------
    const file = e.target.files[0];
    const formData = new FormData();
    formData.append('image', file);
    uploadTheImage(formData); 
    //--------------------------------------------------------------------
  };

the form

<Form.Group>
   <Form.Label>upload your image</Form.Label>
   <Form.Control type='text' onChange={(e) => {console.log(e.target.value);}}/>
   <Form.File
      id='image-file'
      label='choose file'
      custom
      onChange={onChangeUploadImage}
    ></Form.File>
</Form.Group>

number 2 (dosent work)

my function to save stage

const handleSaveStage = (event) => {
    event.preventDefault();
    const dataURL = stageRef.current.toDataURL({
      mimeType: 'image/png',
      quality: 0,
      pixelRatio: 2,
    });
    //dataURL is correct image of stage. i checked it.
    //-----------------------------------------------part 2---------------
    var file = dataURItoBlob(dataURL);
    var formData = new FormData();
    formData.append('image', file);
    uploadTheImage(formData);
    //--------------------------------------------------------------------
  };

the stage

<Stage width={window.innerWidth} height={window.innerHeight} ref={stageRef}>
  <Layer>
    <Text onClick={onSelect} ref={textRef} {...textProps} />
  </Layer>
</Stage>;
<Button onClick={handleSaveImage}>Save Stage</Button>

in the second way i got "Form submission canceled because the form is not connected" and "POST localhost:3000/api/upload 500 (Internal Server Error)" in console

other codes

a function for convert URI to Blob (refrence)

function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
      byteString = atob(dataURI.split(',')[1]);
    else byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i  ) {
      ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], { type: mimeString });
  }

upload the FormData with axios

const uploadTheImage = async (imageObj) => {
    try {
      const config = {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      };
      const { data } = await axios.post('/api/upload', imageObj, config);
      console.log({ data }); //the path(ex: /uploads\image-1632913606047.png)
    } catch (e) {}
  };

CodePudding user response:

I solve it by adding some code that i find from this

const handleSaveStage = (event) => {
    event.preventDefault();
    const dataURL = stageRef.current.toDataURL({
      mimeType: 'image/png',
      quality: 0,
      pixelRatio: 2,
    });
    //dataURL is correct image of stage. i checked it.
    //-----------------------------------------------part 2---------------
    var f = dataURItoBlob(dataURL);
    const file = new File([f], 'capture.png', {
      type: 'image/png',
    });
    var formData = new FormData();
    formData.append('image', file);
    uploadTheImage(formData);
    //--------------------------------------------------------------------
  };
  • Related