使用 Multer 上传图片而不是从 Form

upload image with Multer not from Form

我的代码中有一个图像 URL,我想将它保存为带有 multer 的 FormData。

我尝试了两种使用 multer 保存图像的方法。

number1 完美工作,但 number2 dosent 工作。我认为问题出在 “第 2 部分”

编号 1(有效)

我从表单保存图像的函数

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

形式

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

数字 2(代理工作)

我保存舞台的功能

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

舞台

<div ref={stageRef}>
  ...
</div>;
<Button onClick={handleSaveImage}>Save Stage</Button>

第二种方式我得到了 “表单提交已取消,因为表单未连接”和 控制台中的“POST localhost:3000/api/upload 500(内部服务器错误)”

其他代码

将 URI 转换为 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 });
  }

我通过添加一些我从

中找到的代码来解决它
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);
    //--------------------------------------------------------------------
  };