Posting Images using formData to a Django Rest API - rest

I have a Django Rest API backend and am using a React Native Front End. I wanted to save an image to the rest API.
The POST method used is as follows:
async saveUserData() {
let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN);
var formData = new FormData();
formData.append("bio",this.state.bio);
formData.append("website",this.state.website);
formData.append("phoneno",this.state.phoneno);
formData.append("gender",this.state.gender);
formData.append("avatar",this.state.avatar.uri);
try {
let response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': ' Token '+accessToken,
},
body: formData
});
let responseJson = await response.text();
if(response.status>=200&&response.status<300){
console.log("POST Completed");
}else{
let error=responseJson;
console.log(error);
throw error;
}
return responseJson;
} catch(error) {
return error;
console.error(error);
}
}
I get the following error
{"avatar":["The submitted data was not a file. Check the encoding type on the form."]}
I have also tried this.state.avatar.data and tried to post it but I end up getting the same error. I know that the file upload works fine as I can do it properly from the REST Autogenerated form. What seems to be the problem in the image I am posting?

Here is how you can do it:
var formData = new FormData();
formData.append('avatar', {uri: this.state.avatar.uri, name: 'yourname.jpg', type: 'image/jpg'});
let response = await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
'Authorization': ' Token '+accessToken,
},
body: formData
});

Related

Messed data object in response with Axios

I'm making a request for getting an access_token to an auth0 API.
The request is success, but the data object containing the access token contains weird characters. The thing is that I had that object for 3-4 hours, after that it wasn't retrieved anymore. Any clues on this?
And this is the code:
(async () => {
const client = axios.create({
baseURL: 'https://my_url_to.auth0.com/oauth/token',
headers: {
'Content-Type': 'application/json'
}
});
Log.debug(body);
try {
const resp = await client.post('/', body);
console.log(JSON.stringify(resp.data));
} catch (e) {
Log.error(e);
}
})();
In v1.2.1 fixed this error.
You need to add Accept-Encoding with 'application/json' in axios header.
The default of axios is gzip.
This code will be works
(async () => {
const client = axios.create({
baseURL: 'https://my_url_to.auth0.com/oauth/token',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'application/json'
}
});
Log.debug(body);
try {
const resp = await client.post('/', body);
console.log(JSON.stringify(resp.data));
} catch (e) {
Log.error(e);
}
})();

How to send raw data in flutter http

I wanted to send raw data in flutter http and the data doesn't look like JSON
Here's how I done that in Postman
and tried this in flutter using http,
Response res = await post(
Uri.parse(baseUrl + endPoint),
headers: {'Client-ID': clientId, 'Authorization': 'Bearer $accessToken'},
body: jsonEncode('fields *'),
);
and got this in console,
Error: XMLHttpRequest error.
Add it as this
var headers = {
'Accept': 'application/json',
'Content-Type': 'text/plain',
};
var request = http.Request('POST', Uri.parse('Your url'));
request.body = '''fields *''';
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
Or you can easily see it being implemented in Postman's code request to the right just select the code icon and choose http-Dart

Connecting to WhatsApp API using axios.post using TypeScript

I just started using the WhatsApp Cloud API.
I took the example that was provided on glitch as a reference but there are things that are different since I'm taking the serverless approach.
As seen in glitch's example, it used axios(config) method and I tried it out and it worked fine after minor changes but when I tried axios.post() method I keep on getting the following error:
AxiosError: Request failed with status code 400
The axios(config) method (Which works)
await axios({
method: "POST", // Required, HTTP method, a string, e.g. POST, GET
url:"https://graph.facebook.com/{{Version}}/{{Phone-Number-ID}}/messages?access_token={{Token}}",
data: {
messaging_product: "whatsapp",
recipient_type: "individual",
to: {{Recipient-Phone-Number}},
text: {body: "Welcome back"},
},
headers: {"Content-Type": "application/json"},
});
The axios.post() method (Which doesn't works)
let url = "https://graph.facebook.com/{{Version}}/{{Phone-Number-ID}}/messages"
let payload = {
messaging_product: "whatsapp",
recipient_type: "individual",
to: {{Recipient-Phone-Number}},
text: {body: "Welcome back my friend"},
}
let headers = {"Content-Type": "application/json", "Authorization":"Bearer {{token}}"
}
let params = {}
try
{
const resp = await axios.post(url, {payload}, {headers, params});
log("POST RESP",resp)
}
catch(error)
{
throw error;
}
Try below code.
let url = 'https://graph.facebook.com/<Version>/<Your Phone number ID>/messages';
let payload = {
'messaging_product': 'whatsapp',
'recipient_type': 'individual',
'to': '123456789012',//Recipient Phone Number
'type': 'text',
'text': {
'body': 'Welcome back my friend'
}
};
let headers = {
'Authorization': 'Bearer <Your Temporary access token>',
'Content-Type': 'application/json'
};
axios.post(url, payload, {
headers: headers
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

how post api with authentication identifier and secret in flutter

i want fetch data by post method with identifier and secret in flutter
where should i add "identifier" and "secret" in post method?
in postman they added to body and that works but i couldnt add these to flutter code:
Future post(String url, var data) async {
String url = 'https://member.example.com/includes/api.php';
var data = {
'identifier': 'identifier code otm7LE8OzlBmprXn',
'secret': 'secret code SXZgmDpX8miT31PSRQ',
'action': 'GetInvoices',
'userid': 6414,
'orderby': 'date',
'responstype': 'json',
};
try {
final response = await http.post(
Uri.parse(url),
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json',
},
body: jsonEncode(data),
);
} catch (e) {
print(e);
}
}
E/flutter ( 6118): result=error;message=Authentication Failed

flutter file http request

hello I'm trying to do a post request with JSON and file together how should it be
static Future postApost(String posttitle,image,String value,token) async {
var data = {'posttitle': posttitle, 'post': image.readAsBytes(),'category': value};
await http.post("https://lighte.org/public/api/newpost",headers: {
'Authorization': 'bearer $token',
},body: data).catchError((error) {
print(error.toString());
});
}
static Future postApost(String posttitle,image,String value,token) async {
var request = http.MultipartRequest(
'POST', Uri.parse("https://lighte.org/public/api/newpost"));
//**fromPath()** method is used when you are sending an image from a specific path,
//inCase of String byte Images you have to use the preferred method in MultipartFile class
await http.MultipartFile.fromPath(
'image',
image.path,//use can pass file path here
filename: 'image_name.jpg',
);
request.fields['posttitle'] = posttitle;
request.fields['category'] = value;
request.headers["Authorization"] = 'bearer $token';
}
uploadUserImg (
String filename, String url, File img, String token
) async {
//URI with type of request (POST or GET ...) ---------------
var request = http.MultipartRequest('POST', Uri.parse(url));
//Header type with access token ------------------------
request.headers.addAll({
"Content-Type": "application/json",
'Authorization': 'Bearer $token ',
});
//adding body parameter for request -----------------------
// you can remove this it will not affect the code
request.fields.addAll({
'phone_number': '+201097081508'
});
// adding File image -------------------------------
request.files.add(
http.MultipartFile.fromBytes('image_endpoint', img.readAsBytesSync(),
filename: filename));
//send request + listing to its response
request.send().then(
(response) {
//parsing the response to print it
response. stream.transform(utf8.decoder).listen(
(responseString) {
print(responseString);
});
}