I am passing a blob image file to a server using the header,
application/octet-stream.
I need to also pass some string values to the server with it. If I change the header to
application/json
I can access the string, but the blob becomes undefined.
Example
const data = {
blob,
firstname: 'Nichoals',
};
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.blob())
.then(blob => {
...
})
.catch(error => console.log(error));
},
'image/png',
1,
);
Things I have tried
I have tried to pass the data using FormData() and was able to get the data to the server but the file was corrupt. I do think I could figure out how to get it to work this way but I would like to learn a better way to do it if possible.
Things I do not want to do
I do not want to convert the blob to a string because I fear that will be way to expensive.
Question
In what way can I POST an object with a blob and some string values inside of it to a server without using the way mentioned above?
Essentially this,
const data = {
blob,
firstname: 'Will',
};
You could send the json as a header:
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
'Custom-Json': JSON.stringify(data)
},
body: blob,
}).then(response => response.blob())
.then(blob => {
// handle response
})
.catch(error => console.log(error));
Related
I am ultimately trying to send a fax with the Vitelity API. I have an API on EC2 that I am calling from my React Native app:
// Encoding to Base64
const encodeB64 = () => {
RNFS.readFile(croppedImage, 'base64').then(res => {
sendB64(res);
});
};
const sendB64 = b64 => {
let myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
let raw = JSON.stringify({
data1: b64, // 'jdl3439fdjsle/jjug'
login: {login},
pass: {pass},
faxnum: {destinationNum},
faxsrc: {sourceNum},
recname: 'Test',
file1: 'testfax.jpg',
});
let requestOptions = {
method: 'POST',
headers: myHeaders,
body: raw,
redirect: 'follow',
};
fetch(API_URL, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
};
However, this returns an error cannot POST. If, instead of b64, I change data1's value to something like jdl3439fdjsle/jjug, everything is great.
Do I need to do something special to b64 before I can send it?
My Base64 looks like: /9j/4AA{1.2m more chars}uB//9k=. I've pasted it into a converter and it produces the correct image.
I geuss you have to use a Multipart Form with multipart/form-data as content-type headers if you want to send images. See also this question.
This question already has answers here:
How can I pass POST parameters in fetch request? - React Native
(2 answers)
Closed 1 year ago.
I need to add some parameters to this request:
fetch(url_ticket, {
//body: JSON.stringify(data),
//mode: 'no-cors',
param: {
'token': `${token}`,
'id': `${id}`,
'id_secret': `${id_secret}`
},
method: 'POST'
})
.then(response => {
console.log(response.text());
})
.catch(error => {
console.error(error);
});
However, I'm getting an error. I've made that request in Postman an it works, so the problem is obviously in this code. I think the error is in the params parameter; how can I add properly parameters in this request?
I'm literally new to js, i've searched for answers but i can't understand a thing, so posting my real problem has been my last option
Here is the code to send post request with parameter
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
For info you can read doc here Using fetch
I think this SO answer is a nice and clean way to do it. Basically, it constructs the URL string with parameters.
fetch(url_ticket + new URLSearchParams({
token: `${token}`,
id: `${id}`,
id_secret: `${id_secret}`
}), {});
You could also construct the parameters in a more manual way, by inserting the variables into a backticked URL string:
let url = `${url_ticket}?token=${token}&id=${id}&id_secret=${id_secret}`;
fetch(url, {...})
I want to learn how fetch works. Backend is very simple
<?php
print_r(json_encode($_POST['test']));
And I created this fetch
fetch('http://localhost/test.php', {
method: 'POST',
body: JSON.stringify({
test: 'test'
})
})
.then(res => res.json())
.then(data => console.log(data))
All the time this code return null in console.log. Where I make a mistake?
You have two problems.
Strings and Fetch
If you POST a string using fetch it will default to sending it with a Content-Type: text/plain header.
Plain text isn't JSON. Specify the correct Content-Type.
fetch('http://localhost/test.php', {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
test: 'test'
})
})
PHP won't process JSON formatted requests automatically
You need to read the raw body and parse it yourself. This is a FAQ. Here is the solution.
Here is my code
let formData = new FormData();
// Update the formData object
formData.append(
"myFile",
this.state.product_picture,
this.state.product_picture.name
);
var options = { content: formData };
const token = JSON.parse(localStorage.getItem('token'));
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
product_name:this.state.product_name,
product_description:this.state.product_description,
product_picture:formData,
category_name:this.state.category_choosen,
})
};
fetch('http://cms.test/api/products/insert_supplier_product?token='+token, requestOptions)
.then(response => response.json())
.then(data => {
this.setState({ product: data.product})
})
.catch(error =>{
console.log("Product creation error", error);
});
I have this fetch api its always giving a 422 response I think what is happening is that its not reading a file as I want to upload a file it all works in postman but when using react it crashes
The body here is the problem
inside the state there are some strings but inside the this.state.product_picture there is a file
Hope someone can help! Thank you!
SOLUTION: Using axios to call the api solved my problem
You cannot send a file in a JSON object in a request( atleast not without Base64 encoding it). Change your code in the following way to send a file with your form.
let formData = new FormData();
// Update the formData object
formData.append(
"myFile",
this.state.product_picture,
this.state.product_picture.name
);
formData.append("product_name",this.state.product_name);
formData.append("product_description",this.state.product_description);
formData.append("category_name",this.state.category_choosen);
var options = { content: formData };
const token = JSON.parse(localStorage.getItem('token'));
const requestOptions = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData
};
fetch('http://cms.test/api/products/insert_supplier_product?token='+token, requestOptions)
.then(response => response.json())
.then(data => {
this.setState({ product: data.product})
})
.catch(error =>{
console.log("Product creation error", error);
});
With the console.log I can see the array imagenes and this is ok in proyect react-native, but on the server this variable does not arrive but if I get the array of dates and the variable description on the server
let body = new FormData();
body.append('descripcion', 'dsadsadsa');
body.append('fechas[]', '2018-05-05');
body.append('fechas[]', '2015-05-05');
const {page1, page2, page3, page4, page5} = this.props.items;
body.append('imagenes[]', { uri: page2[2], name:'photo1.jpg', type: 'image/jpg'});
body.append('imagenes[]', { uri: page2[3], name:'photo2.jpg', type: 'image/jpg'});
body.append('imagenes[]', { uri: page2[4], name:'photo3.jpg', type: 'image/jpg'});
fetch(url, {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: body
})
.then(res => res.text())
.then(res => {
console.log(res)
}).catch((err) => {
console.log('err', err)
});
});
Thanks for help me!
the code upload data and file (images) in RN this is ok, the bug in vars size file php.ini (memory_limit, upload_max_filesize, post_max_size).
in nginx, edit file nginx.conf add or update command
client_max_body_size 500M
Link https://www.cyberciti.biz/faq/linux-unix-bsd-nginx-413-request-entity-too-large/