react native upload image with axios - reactjs

I have this data
came from react-native-image-picker
data: "/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2Qtan" => 90kb
fileName: "77677.jpg"
fileSize: 67542
height: 600
isVertical: true
originalRotation: 0
path: "/storage/emulated/0/Download/77677.jpg"
type: "image/jpeg"
uri: "content://media/external/images/media/18584"
width: 399
__proto__: Object
and am try to set this data in object type #FromData to upload #img
var binaryDataInBase64 = new FormData();
binaryDataInBase64.append('file', {
// data: response.data,
uri: 'file://' + response.uri,
name: 'MMM.jpg',
type: response.type
})
console.log('=======================>', binaryDataInBase64)
axios.post(
'https://danskeclouddemo.com/api/file',
{ file: binaryDataInBase64 },
{ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'multipart/form-data' } }
).then(res => {
console.log(res)
}).catch(error => {
console.log(error)
})
and this is BackEnd Postman Working good Postman collection
//======================
//======================
Edit
Some people talk about the problem from react native version after 0.61.5
in this link issues

Your form data must be like that.
formdata.append('file',{
uri: Platform.OS === 'android' ? photo.uri : 'file://' + photo.uri,
name: 'test',
type: 'image/jpeg' // or your mime type what you want
});
Then
axios.post('/users/profilepic', formdata, config).then((res) => {
console.log(res.data);
return res.data;
});

Rather using, axiom use fetch simple, approach to upload, image
this.setState({imageLoading:true})
const credentials={
userId:this.state.userId
}
try {
let response = await fetch(
'url',
{
'method': 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: createFormData(source, credentials)
}
);
if (response.status == 200) {
response.json().then(data => {
switch (data.status) {
case 200:
break;
}
});
}else {
this.setState({imageLoading:false ,isLoading:false})
}
} catch (error) {
this.setState({imageLoading:false,isLoading:false})
console.error(error);
}
const createFormData=(image,body)=>{
var data = new FormData();
data.append(image, {
uri: Platform.OS === "android" ? image.uri : image.uri.replace("file://", ""),
name: `dummy${Date.now()}.jpg`,
type: 'image/*'
})
Object.keys(body).forEach(key => {
data.append(key, body[key]);
});
return data
}

Related

Send images to backend using ReactJS

I want to make a post request to backend with all form data.
Uploading the images i get an array with data:
const normFile = e => {
const getFileList = e.fileList.map( i => i.originFileObj);
console.log('Upload event:', getFileList);
fetch('https:///uploadapi', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ images: getFileList })
})
.then(async response => {
const data = await response.json();
console.log(data, 'res data')
})
.catch(error => {
console.error('There was an error!', error);
});
if (Array.isArray(e)) {
return e;
}
return e && e.fileList;
};
Above is my code where i use Ant Design uploader.
But how to delete the File text before each object?
You have to use multipart/form-data header
Let's say you have an input
<input type="file" onChange={uploadFile}/>
And logical part:
uploadFile = (e) => {
const formData = new FormData();
formData.append('name_your_file', e.target.files[0])
fetch('https:///uploadapi', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData
})
}

What link do I call to Amazon s3 when I use axios

I'm new to S3 so I didn't find anywhere in the API where it says that this is the respective URL to use for the axios URL parameter. I'm keeping on getting a 404 error saying that the
axios({
url: `call/s3/backend`,
method: "post",
data: {
//images: imageArray.toByteArray(),
},
})
.then((res) => {
//imageUrlArr = res.data;
axios({
url: `api/petition_posts`,
method: "post",
data: {
petition_post: {
title: title,
description: description,
hashtags: arrayOfHashtags.join(" "),
amount_donated: 0,
//media: imageUrlArr,
goal: money,
card_type: "petition",
org_profile_id: 1,
},
},
})
.then((res) => {
console.log(res.data);
})
.catch((error) => console.log(error));
})
.catch((error) => console.log(error));
}
titleError(true ? title.length === 0 : false);
descriptionError(true ? description.length === 0 : false);
};
To upload a file from the browser to S3 using Axios:
fetch a pre-signed S3 URL from your server
PUT the file to the pre-signed URL using Axios
Server:
const aws = require('aws-sdk')
aws.config.update({
accessKeyId: '...',
secretAccessKey: '...'
})
const s3 = new aws.S3()
const params = {
Bucket: 'my-bucket',
Key: 'my-file.txt',
Expires: 300,
ContentType: 'text/plain'
}
s3.getSignedUrl('putObject', params,
(error, signedUrl) => return signedUrl /* to client */ )
Client:
const axios = require('axios')
axios.put(<signed-url-from-server>, 'abc', {
headers: {
'Content-Type': 'text/plain'
}
}).then(res => console.info(res))
.catch(err => console.error(err))

Bad Request React Axios 400

Can Anyone tell me why I am having this error??
the error is status code 400 bad request
This could be on the server?
I am new with react
handleSubmit(event, _success, _error) {
event.preventDefault();
var data = {
FriendlyName: this.state.FriendlyName,
full_name: this.state.full_name,
email: this.state.email,
};
const config = {
method: 'post',
url:
'https://taskrouter.twilio.com/v1/Workspaces/{<WorkerSid>}/Workers',
headers: {
Authorization:
'Basic QUM1MmNiOTIxNGQwY2ZmMjA4NjBiZDdjMTQ5Y2Q4NjBlNTpmODRmOWJiOGFlZjI4MWFmZDY2NGY4NTY1OGYwNzJhOA==',
'Content-Type': 'application/x-www-form-urlencoded',
},
data: data,
};
axios(config)
.then(() => {
console.log('data', data);
if (Object.keys(data).length > 0) {
if (typeof _success === 'function') _success(data);
} else {
if (typeof _error === 'function')
_error({ error: 'Não houve nenhum retorno.' });
}
})
}
Try backticks instead of apostrophe url:'https://taskrouter.twilio.com/v1/Workspaces/{<WorkerSid>}/Workers'
const config = {
method: 'post',
url:
'https://taskrouter.twilio.com/v1/Workspaces/{<WorkerSid>}/Workers',
headers: {
Authorization:
'Basic QUM1MmNiOTIxNGQwY2ZmMjA4NjBiZDdjMTQ5Y2Q4NjBlNTpmODRmOWJiOGFlZjI4MWFmZDY2NGY4NTY1OGYwNzJhOA==',
'Content-Type': 'application/x-www-form-urlencoded',
},
data: data,
};

react native post form data with object and file in it using axios

so i want to upload
object as data
and file as Note
to api using axios
uploadToServer= () => {
const file =this.state.photo
let data2 ={sale_id:1,
note_type_id:4,
description:"test",
note_content_item:" hi from broker hub"
}
let data = new FormData()
data.append('data[sale_id]', '1')
data.append('data[note_type_id]', '4')
data.append('data[description]', "test")
data.append('data[note_content_item]', "test")
console.log(data)
axios({
url: api',
method: 'POST',
data: data,
headers: {
'Content-Type' : 'multipart/form-data',
'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='
}
})
.then(resp => console.log(resp.data.response))
.catch(error => console.error(error));
}
first i am trying with data without Note i can do it in postman
but with my code i got error
message: "Can not save file"
response_code: 10
i got this error only if i change the key from data to something else
when you are using react-native you don't need "form-data" package. Because react native polyfills standard FormData api and exports it as global.
second problem is axios converts form data automatically to string, so you need to use transformRequest config on request to override it.
import { AxiosRequestConfig } from "axios";
const FormData = global.FormData;
const axiosInstance = axios.create({
baseURL: 'example.com', // use with scheme
timeout: 30000,
headers: {
"X-Platform": 'iOS',
"X-App-Build-Number": '1.0.0',
},
});
const formData = new FormData();
formData.append("userId", "123456");
formData.append("file", {
uri: "/dev/sda/abc.png",
type: "image/png",
name: "abc.png",
});
const config: AxiosRequestConfig = {
method: "post",
url: "/process/start",
responseType: "json",
headers: {
'Content-Type': 'multipart/form-data',
// if backend supports u can use gzip request encoding
// "Content-Encoding": "gzip",
},
transformRequest: (data, headers) => {
// !!! override data to return formData
// since axios converts that to string
return formData;
},
onUploadProgress: (progressEvent) => {
// use upload data, since it's an upload progress
// iOS: {"isTrusted": false, "lengthComputable": true, "loaded": 123, "total": 98902}
},
data: formData,
};
// send post request and get response
const response = await axiosInstance.request(config);
You are not building FormData correctly, Try this:
let data = {sale_id:1,
note_type_id:4,
description:"test",
note_content_item:" hi from broker hub"
}
const formData = new FormData();
formData.append('data', JSON.stringify(data));
formData.append('Note', {
uri: "file://" //Your Image File Path
type: 'image/jpeg',
name: "imagename.jpg",
});
axios({
url : api,
method : 'POST',
data : formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization':'Basic YnJva2VyOmJyb2tlcl8xMjM='
}
})
.then(function (response) {
console.log("response :", response);
})
.catch(function (error) {
console.log("error from image :");
})
This might help you:
import {Platform} from 'react-native';
import axios from 'axios';
const upload = async readPath => {
console.log('path', readPath);
const URL = 'your-url';
const headers = {
headers: {
'Content-Type': 'multipart/form-data',
Accept: 'application/json',
Authorization: `Bearer ${projectSecret}`,
},
};
const formData = new FormData();
const file = {
uri:
Platform.OS === 'android' ? `file:///${readPath}` : readPath,
type: 'text/plain',
name: name,
};
formData.append('file', file);
await axios
.post(URL, formData, headers, {
timeout: 3000,
})
.then(async response => {
console.log(response.data);
})
.catch(error => {
console.log('error : ', error);
});
};

React-Native image upload

Is it possible to upload file (images) to server with react-native using FormData? Tried to use it like this:
var data = new FormData();
data.append('file', file);
console.log(JSON.stringify(data));
var id = 5;
fetch('http://192.168.1.104:3000/app/complaint/uploadFile?id='+id,{
method:'POST',
body: data,
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data;',
},
});
For React, FormData works as expected but for React-Native not working.
I have also tried (used in react - working)
const data = fetch('http://192.168.1.104:3000/app/complaint/uploadFile?id='+id, {
credentials: "same-origin",
method:'POST',
body: dataval,
timeout: 1000000000,
});
But nothing works,
In the back-end server, I am upload using
var d = require('domain').create()
d.run(function safelyUpload () {
var file=req.file('file').upload({dirname: path.resolve(sails.config.appPath, folder),
}, function whenDone(err, uploadedFiles) {
if (err) return res.serverError(err);
else{
sails.log.debug('Complaint File data : ' +util.inspect(uploadedFiles, {showHidden: true,depth: null}));
}
});
});
Is there any other ways
Here is example to upload image using Fetch API
const photo = {
uri: user.profilePicture,
type: 'image/jpeg',
name: 'photo.jpg',
};
const form = new FormData();
form.append("ProfilePicture", photo);
fetch(
URL,
{
body: form,
method: "PUT",
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + user.token
}
}
).then((response) => response.json())
.catch((error) => {
alert("ERROR " + error)
})
.then((responseData) => {
alert("Succes "+ responseData)
}).done();
Credits https://stackoverflow.com/a/36649457/5315786

Resources