React Native iOS app cannot upload image via Express + multer server

Replace the Iative IOS app; want to download an image; from the device. RN 0.39.2

Customer:

const formData = new FormData() formData.append('files', file) formData.append('type', 'image') fetch(API_HOST+UPLOAD_AVATAR,{ method:'post', headers: {'Content-Type':'multipart/form-data;boundary=6ff46e0b6b5148d984f148b6542e5a5d','Authorization': 'Bearer'+' '+token}, body: formData }) .then(response=>response.json()) .then(data=>{ //console.log(data) //Alert.alert(data) }) .catch(error=>{ console.log(error) }) 

Server:

 var multer = require('multer'); var upload = multer(); router.post('/user', ensureAuthenticated, upload.any(), function (req, res) { console.log(req.body); console.log(req.files); }) 

Error:

The req.body server and req.files are empty.

Then I try to use RNFetchBlob.

  RNFetchBlob.fetch('POST', API_HOST+UPLOAD_AVATAR, { 'Content-Type':'multipart/form-data;boundary=6ff46e0b6b5148d984f148b6542e5a5d' 'Authorization' : 'Bearer'+' '+token }, formData) .then((resp) => { }).catch((err) => { // ... }) 

then the error will change to

NSMutableDictionary cannot be converted to NSString.

And req.body - {}, req.files - undefined

+6
source share
1 answer

I suppose you have found a solution for this, if so, could you share? In any case, for the RNFetchBlob problem, I used to get the same error, and I decided by changing FormData to an array. Like this:

 const body = [{ name: 'data', data: JSON.stringify(whateverData) }, { name: 'file', data: filePath, }]; … RNFetchBlob.fetch('POST', apiEndpoint, headers, body); 

Hope this helps.

0
source

Source: https://habr.com/ru/post/1015637/


All Articles