简体   繁体   English

React Native 上传图片失败

[英]React Native Failed Upload Image

I am struggling from the past 2 days to crack the file/image upload with React Native to MongoDB.从过去 2 天开始,我一直在努力使用 React Native 来破解文件/图像上传到 MongoDB。 I literally read all the related forums but there is no luck.我真的阅读了所有相关的论坛,但没有运气。 I read couple of forums and they gave a sample example but I wasn't succeeded.我阅读了几个论坛,他们给出了一个示例,但我没有成功。 Here are the sample codes that I wrote.这是我编写的示例代码。

Client Side :客户端 :

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

Server Side服务器端

 var storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, __basedir + '/resources/static/assets/uploads'); }, filename: (req, file1, cb) => { console.log("file : ", file); let name = file.originalname || file.name; let extension = name.substr((~-name.lastIndexOf(".") >>> 0) + 2); let filename = generateId() +"."+ extension; nsion; cb(null, filename) }, }); var upload = multer({ storage: storage, limits: { fileSize: 1024 * 1024 * 5 } });

Result结果

在此处输入图片说明

Try out the below试试下面的

      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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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