I have photo file taken with ImagePicker, and I need upload it to server, using axios, and I need send type as a string with this photo.
My code here
const axiosMultipart = axios.create({
timeout: 3000,
baseURL: BASE_URL,
headers: {
'Content-Type': 'multipart/form-data'
}
})
uploadDocs(token,type,photo){
let data = new FormData();
data.append('photo', photo);
data.append('type', type);
return axiosMultipart
.post(
`uploadDocs`,
{data},
{
headers: {
Authorization: token,
},
}
)
.then((response) => {
return response.data;
})
.catch((error) => console.log("uploadDocs: " + error));
};
Server response is error_code 400
What is wrong here?
Also I have code on php with a working request
Try With Below Code,
var photo = {
uri: file,
type: 'image/jpeg',
name: 'photo.jpg',
};
var FormData = require('form-data');
var form = new FormData();
form.append('photo', photo);
form.append('filetype', filetype);
axios({
method: 'post',
headers: {
"Accept": "application/json",
'Content-Type': 'multipart/form-data',
"Authorization": authData
},
data: form,
url: `${base_url}`,
}).then(async (result) => {
console.log("uploadFile detail Response===>", result);
}).catch((error) => {
console.log("uploadFile detail error===>", error);
callback({ status: false, result: error })
});
Related
I have been trying to make a post request to send formData using axios / fetch, but every time i make a request it throws "Network Error". I have been trying this for couple of days but couldn't do it.
var file = new File([this.state.selectedFileObj], "ISDD_" + this.state.fileName, { lastModified: new Date().getMilliseconds() })
formdata.append("file", file, this.state.fileName);
formdata.append("folderName", this.state.folderName);
formdata.append("userName", "user#domain.com");
formdata.append("documents", documents);
// 1st approach
RNFetchBlob.fetch('POST', url, {
"Content-Type": 'multipart/form-data',
"enctype": 'multipart/form-data',
"Cache-Control": 'sno-cache',
"Pragma": 'no-cache'
}, formdata)
.then((response) => console.log(`1 ${response.text()}`))
.then((RetrivedData) => {
console.log(`2 ${RetrivedData}`);
})
.catch((err) => {
console.log(`err ${err}`);
})
//2nd approach
axios({
url: url, formdata,
method: 'POST',
headers: {
"Content-Type": 'multipart/form-data',
'enctype': 'multipart/form-data',
'Cache-Control': 'sno-cache',
'Pragma': 'no-cache'
},
data: formdata
})
.then((response) => {
console.log(`1 ${response}`)
})
.catch((error) => {
console.log(error)
})
Need a solution for it,
Thanks,
i'm trying to upload FormData which include text ,image,pdf etc
I am using axios.
Axios Call
const sellerRegister = params => {
console.log(params);
return dispatch => {
dispatch(servicePending());
return axios
.post(`${BaseUrl}/seller/register`, params, {
headers: {
Accept: "application/json",
"Content-type": `multipart/form-data; boundary=${params._boundary}`
}
})
.then(res => {
return dispatch(sellerRegisterSuccess(res));
})
.catch(err => {
return dispatch(serviceError(err.message));
});
};
};
Params in FormData
ServiceError
Provide solutions of this error. and also guide me am i doing this in right way or not ?
Thanks
Using the latest version of Axios, you make an HTTP request with 'Content-Type': 'multipart/form-data' in the header as follows:
const formData = new FormData();
formData.append('action', 'ADD');
formData.append('param', 0);
formData.append('secondParam', 0);
formData.append('file', new Blob(['test payload'], { type: 'text/csv' }));
axios({
url: 'http://your_host/api/auth_user',
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
}
})
use url instead of uri.
or
You can do simply:
axios.defaults.headers.common['Content-Type'] = 'multipart/form-data;
boundary=someArbitraryUniqueString';
For a project we need to upload an image file which has memory above 2mb.\
which we are not able to upload through base64 conversion.
Any help could be usefull
Once you have your local image url using ImagePicker or some another solution, here's how you can send it to your server:
const formData = new FormData();
formData.append("image", { uri: imageUrl, name: 'image.jpg', type: 'multipart/form-data' })
fetch(yourUrl, {
method: "POST", {
'Content-Type': 'multipart/form-data',
},
body: formData
);
Use any request library e.g axios . Then try with form data. To pick the image from device/camera you can use react-native-image-picker.
import ImagePicker from 'react-native-image-picker'
ImagePicker.showImagePicker(options, response => {
console.log(response.data)
});
Below is what helped me.
In android/app/src/main/java/com/{yourProject}/MainApplication.java
comment the below line :
initializeFlipper(this, getReactNativeHost().getReactInstanceManager())
In android/app/src/debug/java/com/{yourProject}/ReactNativeFlipper.java
comment in line 43 :
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
Code for image upload :
var formData = new FormData();
formData.append('UserId', 'abc#abc.com');
formData.append('VisitId', '28596');
formData.append('EvidenceCapturedDate', '09/10/2019 13:28:20');
formData.append('EvidenceCategory', 'Before');
formData.append('EvidenceImage', {
uri: Platform.OS === 'android' ? `file:///${path}` : path,
type: 'image/jpeg',
name: 'image.jpg',
});
axios({
url: UrlString.BaseUrl + UrlString.imageUpload,
method: 'POST',
data: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
},
})
.then(function (response) {
console.log('*****handle success******');
console.log(response.data);
})
.catch(function (response) {
console.log('*****handle failure******');
console.log(response);
});
I'm trying to receive a token from Spotify api. Unfortunately I keep on receiving 415. Could you help me and let me know what am I doing wrong?
const axios = require('axios');
const getToken = (code) => {
return axios({
method: 'post',
url:'https://accounts.spotify.com/api/token',
form: {
code,
grant_type :'authorization_code',
redirect_uri: process.env.SPOTIFY_REDIRECT
},
headers: {
'Authorization': 'Basic ' + (new Buffer(process.env.SPOTIFY_ID + ':' + process.env.SPOTIFY_SECRET).toString('base64')),
'Content-Type': 'application/json'
}
}).then(token => {
return token;
}).catch(e=> {
console.log(e);
return e.response;
});
};
module.exports = {
getToken
};
415 error code is related to problem with wrong content type or content encoding, (https://httpstatuses.com/415)
I do not know axios but please take a look on the example on spotify github https://github.com/spotify/web-api-auth-examples/blob/master/authorization_code/app.js#L74
According to this issue on github (https://github.com/spotify/web-api/issues/321), try to use content-type 'Content-Type': 'application/x-www-form-urlencoded'
There is example withs axios
axios({
url: "https://accounts.spotify.com/api/token",
method: "post",
params: {
grant_type: "client_credentials"
},
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded"
},
auth: {
username: "YOUR-CLIENT-ID",
password: "YOUR-CLIENT-SECRET"
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
});
It works!!!
What I've done was:
- change Content-Type for 'application/x-www-form-urlencoded'
- client_id and client_secret were taken from header and posted before grant_type in body
- changed 'data' to 'params'
const axios = require('axios');
const getToken = (code) => {
return axios({
method: 'post',
url:'https://accounts.spotify.com/api/token',
params: {
client_id: process.env.SPOTIFY_ID,
client_secret: process.env.SPOTIFY_SECRET,
code,
grant_type :'authorization_code',
redirect_uri: process.env.SPOTIFY_REDIRECT
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(token => {
return token;
}).catch(e=> {
return e.response.data;
});
};
And it resulted with a beautiful looking token \m/
After spending one hour trying to figure out how to get the token, I came up with this answer! :)
const axios = require('axios');
const express = require('express');
const app = express();
const client_id= 'YOURCLIENTID';
const client_secret = 'YOURCLIENTSECRET';
app.get('/api/token', (req, res) => {
axios({
method: 'post',
url: 'https://accounts.spotify.com/api/token',
headers: {
'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64')),
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
grant_type: 'client_credentials'
},
json: true,
})
.then(body => {
res.send(body.data.access_token);
})
.catch(e => {
console.log(e.response.data);
});
});
app.listen(3000, () => {
console.log('Server Listening on port 3000');
});
If you making API call from client side (browser), try this solution:
getTokken() {
const urlSpotify = "https://accounts.spotify.com/api/token";
axios({
method: "post",
url: urlSpotify,
data: "grant_type=client_credentials",
headers: {
Accept: "application/json",
"Content-Type": "application/x-www-form-urlencoded",
},
auth: {
username: process.env.REACT_APP_SPTID_KEY, // User ID
password: process.env.REACT_APP_SPCS_KEY, // User Secret
},
})
.then((response) => {
console.log(response);
})
.catch((err) => console.log(err));
}
I have my video file assets-library://asset/asset.mov?id=766BDDA3-F0EB-43B3-B719-4EA851692B91&ext=mov and I am trying to now upload it to my Express server.
const uri = 'http://localhost:3000/upload';
const formData = new FormData();
formData.append('file', 'assets-library://asset/asset.mov?id=766BDDA3-F0EB-43B3-B719-4EA851692B91&ext=mov');
fetch(uri, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data boundary=gc0p4Jq0M2Yt08jU534c0p'
},
body: formData
})
.then(res => {
console.log({ res });
})
.catch(err => {
console.log(err);
});
My Express Server API endpoint:
app.post('/upload', upload.single('file'), (req, res) => {
console.log(req.file);
res.send('Done');
});
The console.log(req.file) returns undefined.
Do I need to do an extra step in between?
As per Gavin's comment, I tried out RNFetchBlob.
RNFetchBlob.fetch(
'POST',
'http://localhost:3000/upload',
{
'Content-Type': 'multipart/form-data'
},
[
{
name: 'file',
filename: 'vid.mov',
data: RNFetchBlob.wrap(file)
}
]
)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
});
My application crashes without any logs on Xcode or in the Debugger.