React native file upload using dropzone to flask - react-native

Hi I want to upload file using React native to flask server
I sent a file using fetch function and I received response. But print(request.files) result ImmutableMultiDict([]) how to I see my file in server? I checked state was right and I got response {'state' : 'ff'}
react native
pressSumbitButtom() {
var formData = new FormData()
formData.append('file', this.state.file)
return fetch('http://127.0.0.1:8000/file/', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
}).then(res =>
res.json()
).then(data => console.log(data))
}
App.py
#app.route("/file/", methods=['GET', 'POST'])
#cross_origin(origin='*', headers=['Contect-Type'])
def get_filepath() :
response = jsonify({'state':'ee'})
if request.method == 'POST' :
print('response: ',response, 'request: ', request)
print(request.files)
response= jsonify({'state':'ff'})
return response
return response

Related

Fetch Post of formData with images works in iOS but on android returns 400 BAD REQUEST

`I am using fetch on react native to send a post request with a form data object on the body.
This code works on iOS but on android it returns a 400 BAD REQUEST and I get ERROR [SyntaxError: JSON Parse error: Unexpected EOF].
const buildFormData = () => {
const data = new FormData();
for (let i = 0; i < photoForm.photosToUpload.length; i++) {
console.log(photoForm.photosToUpload[i].uri)
data.append('photosToUpload', {
uri: photoForm.photosToUpload[i].uri,
name: photoForm.photosToUpload[i].fileName,
type: 'image/jpeg'
});
data.append("userForm", JSON.stringify(userForm));
console.log(data)
return data;
}
This is how I am building my form data.
export const createUser = (formData) => async (dispatch) => {
try {
const headers = {
'Content-Type': 'multipart/form-data'
};
const response = await fetch('https://c66d-2a02-a03f-a5a1-e400-1573-78c6-e019-e601.eu.ngrok.io' + '/create_user', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData,
})
.then(response => response.json())
.then(responseJson => {
console.log(responseJson);
})
.catch(error => {
console.error(error);
});
Handle successful response
catch (error) {
Handle error
}
This is how I am sending the form data to my django server. I know the problem is in the form data because if I dont send files the request goes through.
I have read almost every github issue on this matter, switched to axios, tried multiple solutions and no luck. Does anyone know what the problem can be?
I tried to make a post request using fetch and it works on iOS but not on android.
I was expecting to work on both OS.`

The body parameters are not working in fetch post react native

I have a post request from react native app to chragebee for creating new customer, in postman it works fine, and in the app it works fine also, but the problem is in passing the body parameters from the app to chargebee, so i can not see for example the body parameters in the response body return from chargebee like the email, firstname, lastname , .... after creating user from the app, whereas in postman i can see them.
The postman post request
The response in postman
The response in postman if i remove the body parameters
The function responsible for signup process in react native :
export const ChargebeeCreateUser = (first_name,last_name,email) => {
const bodyParams = {
first_name: first_name,
last_name:last_name,
email:email,
};
return fetch(`https://editpress-test.chargebee.com/api/v2/customers`, {
method: 'POST',
headers: new Headers({
'Authorization': 'Basic ' + encode('site_api_key'),
'Content-Type': 'application/json'
}),
body: JSON.stringify(bodyParams)
})
.then((response) => response.json())
.then(responseJson => {
return responseJson
})
}
Calling the function:
register = async () => {
const { given_name,family_name,email, password } = this.state
let ChargebeeCreateUserResponse = await
ChargebeeCreateUser(given_name,family_name,email);
console.log(ChargebeeCreateUserResponse);
---
---
---
The result of console.log(ChargebeeCreateUserResponse):

Network Error when sending file in react native with axios

I am trying to send a file to a nodejs server from react native using axios, this is my code:
const createFormData = (file) => {
const data = new FormData();
data.append('message', text);
data.append('receiver',doctorid);
if(file !== ''){
data.append('file', {
type: file.type,
uri: file.uri,
name: file.name.replace(/\s/g,'')
})
}
return data;
}
const onSend = async() => {
const newMessages = [...messages]
newMessages.push({"sender": currentuserID, "id": 339, "message": 'sending...', "attachment": '', "receiver": doctorid, "type": 0},)
setMessages(newMessages)
const token = await AsyncStorage.getItem('token');
const data = createFormData(singleFile)
await appApi.post('/chats', data, {
headers: { 'Authorization': 'Bearer ' + token }
}).then(()=>{
socket.emit('sendmessage', text, (err) => {
messageInit()
});
})
.catch(err => console.log(err.message))
}
This code works perfectly if there's no image attached, but ones there's an image attached, I get the network error message immediately.
For a little bit of troubleshooting, I tried sending request to my local machine, using ngrok. From ngrok, I realized the request wasn't sent at all to the url. So it just fails immediately, without the request been made to the url.
Anyone with solution to this.
I'm testing on an android emulator
send using formdata
try this
let formData = new FormData();
let imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})

Is there a limit in the body of a request to an api in React native?Because i cant send large base64 to server

It says me syntax error: JSON Parse error. unrecognized token '<'
Iam using Fetch to do the request.It let me send short base64 strings i tried so what can i do?
This is my call to the api:
export function uploadPost(post) {
let data = {
body: post.body,
picture: post.picture,
type: post.type,
user: {
_id: post.user._id,
name: post.user.name,
picture: post.user.picture
}
}
var headers = {
'Content-Type': 'application/json',
'Access-Control-Origin': '*'
}
return fetch(URL + "/uploadPost", {
method: "post",
headers: headers,
body: JSON.stringify(data)
})
.then(response => Promise.resolve(response.json()))
.catch(err => {
return Promise.reject(err);
})
}
I finally solved it. The problem was that the response was returning a 413 status and I found out that means payload too large. So I added to my node js express server this lines:
var app = express();
//after
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

Post to /upload from react native

I'm trying to upload a picture to strapi from react native.
async function uploadPicture(uri) {
var data = new FormData();
data.append('files', {
uri: uri.replace('file://', ''),
name: uri,
type: 'image/jpg'
});
// Create the config object for the POST
// You typically have an OAuth2 token that you use for authentication
const config = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data;'
},
body: data
};
const fetchPromise = fetch('http://<host>:1337/upload', config)
console.log(fetchPromise)
return await fetchPromise
}
I get a 200 status code but no new picture is listed on the uploads page.
Oh! I figured it out using simple-http-upload-server to test the uploads. The problem was that I was setting the name of the file to be the uri. This would probably cause an error on strapi when creating the file on the server folder. It should return an error code nonetheless.