反应本机失败的上传图像

时间:2019-12-07 14:48:08

标签: javascript node.js react-native expo multer

过去2天,我一直在努力破解使用React Native将文件/图像上传到MongoDB的问题。我从字面上看过所有相关的论坛,但是没有运气。我读了几个论坛,他们举了一个例子,但是我没有成功。这是我编写的示例代码。

客户端:

  $.ajax({
      url: "/templates/dir.php",
      type: "POST",
      success: function(output) {
          console.log(output);
      }
  });

服务器端

const { uri } = await this.camera.takePictureAsync(options);

let formData = new FormData();
formData.append('file', {
  uri: uri.replace("file:///", ""),
  type:'image/jpg', name:'userProfile.jpg',
});

const rawResponse = await fetch('http://192.168.1.5:9000/api/contrats/upload', {
  method: 'POST',
  body: formData,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'multipart/form-data; charset=utf-8',
    },
});


const content = await rawResponse.json();

console.log(content);

结果

enter image description here

1 个答案:

答案 0 :(得分:0)

尝试以下

      let body = new FormData();
       let filename = uri.split('/').pop();
       body.append('file',  {uri:uri, name:filename, type:'image/jpg', });
       const header = {
           'Accept': 'application/json',
           'content-type': 'multipart/form-data',
         }
           fetch("http://192.168.1.5:9000/api/contrats/upload", {
               method: 'POST',
               headers: header,
               body:body,
           }).then(response => response.json())
            .then(res => console.log(res))
            .catch(err => console.log("err", err)
相关问题