I'm trying to send images from my form to my php webservice.
For now, I'm just trying to see if i receive it well.
and with this code:
html:
<input type="file" multiple name="images" id="images" />
<button class="bouton" id="valider">envoi</button>
Js:
const sample_image = document.getElementById('images');
const valider = document.getElementById('valider');
valider.addEventListener('click', () => {
upload_image(sample_image.files[0]);
})
const upload_image = (file) => {
const form_data = new FormData();
form_data.append('sample_image', file);
console.log(form_data);
fetch(host+"add.php", {
method: "POST",
body:form_data
}).then(response => response.json())
.then(response => {
console.log(response);
});
}
Php:
echo json_encode($_FILES['sample_image']);
It's working but only for 1 image, but i need send many.
and when i try to change my JS to :
upload_image(sample_image.files);
(without the [0])
it's not working.
I just wanted to send an array of files and then use it in my php, but it says
Notice: Undefined index: sample_image
Does it exists a way to do it ?
Thank you.
it's working with :
const upload_image = (files) => {
const form_data = new FormData();
let compt = files.length;
for(let i=0;i<compt;i++)
{
form_data.append('sample_images[]', files[i]);
}
console.log(files.length);
console.log(form_data);
fetch(host+"add.php", {
method: "POST",
body:form_data
}).then(response => response.json())
.then(response => {
console.log(response);
}); }
thank you everyone !
You need to change the FormData to receive an array instead of a single item:
const upload_image = (files) => {
const form_data = new FormData();
form_data.append('sample_images[]', files);
console.log(form_data);
fetch(host+"add.php", {
method: "POST",
body:form_data
}).then(response => response.json())
.then(response => {
console.log(response);
}); }
Related
I have the following code, where I have an array of images images and uploading each image in that array. the code is working fine, but I have an issue, where all the uploaded images have the same name ex: storage/1671621889.png.
const uploadData = async (data) => {
const attachment = []
const url = `http://127.0.0.1:8000/api/file/upload`
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
await Promise.all(images.map(async (file, index) => {
const imageData = new FormData()
imageData.append('file', file)
imageData.append('fileName', file?.name)
let result
axios.post(url, imageData, config)
.then(function(response) {
result = response.data.data.file
attachment.push(result)
})
}))
.then(() => {
submit(data, attachment)
})
}
I tried awaiting the request, but that doesn't change anything.
You're defining your upload file name already as file?.name. If you must make it unique for each request, you can simply append the index.
const uploadData = async (data) => {
const attachment = []
const url = `http://127.0.0.1:8000/api/file/upload`
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
await Promise.all(images.map(async (file, index) => {
const imageData = new FormData()
imageData.append('file', file)
imageData.append('fileName', `${file?.name}_${index}`)
let result
axios.post(url, imageData, config)
.then(function(response) {
result = response.data.data.file
attachment.push(result)
})
}))
.then(() => {
submit(data, attachment)
})
}
I have a problem with fetch and Ionic 6. It is not sending image data to the server.
The code is as follows:
let formData = new FormData();
formData.append('photo', pathImage);
fetch(this.MAIN_URL + '/uploadAvatar?token=' + token, { method: 'POST', body: formData})
.then(response => response.json())
.then(data => {
alert(JSON.stringify(data));
})
.catch(error => {
alert(JSON.stringify(error));
})
Thing is, the image data is not being sent to the server. The variable pathImage comes from Ionic's Crop plugin, and it is like this:
file:///storage/emulated/0/Android/data/io.ionic.starter/cache/(random_number).jpg
I think it is not getting the data from pathImage, but how can I change that? I tried turning pathImage into a blob but that didn't work either.
After doing some research, here is the answer to my question:
let formData = new FormData();
const file = await Filesystem.readFile({ path: pathImage.split('?')[0] });
let blob = new Blob([this.fixBinary(atob(file.data))], { type: 'image/jpeg' });
formData.append('photo', blob);
fetch(this.MAIN_URL + '/uploadAvatar?token=' + token, { method: 'POST', body: formData})
.then(response => response.json())
.then(data => {
alert(JSON.stringify(data));
})
.catch(error => {
alert(JSON.stringify(error));
})
Where fixBinary is a function that fixes the binary data coming from the jpg file:
fixBinary (bin: any) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
Now, if I pick and crop a file, the end result is uploaded to the server just fine.
SO I am calling 5 APIs in my js file and the code is the same for all except the URL and the form data I am passing. and same lines of code repeats 5 times and I think this is not the good of writing. What I want is to make this code dry but don't know what changes I should make
var formdata = new FormData();
formdata.append("market", "KSE100");
var requestOptions = {
method: "POST",
body: formdata,
redirect: "follow",
};
fetch(
"api_url here_1",
requestOptions
)
.then((response) => response.json())
.then((stockData) => console.log('aasfs',stockData ))
.catch((error) => console.log("error", error));
var formdata = new FormData();
formdata.append("symbol", "SYS");
var requestOptions = {
method: "POST",
body: formdata,
redirect: "follow",
};
fetch(
"api_url here_2",
requestOptions
)
.then((response) => response.json())
.then((stockData) => console.log('aasfs',stockData ))
.catch((error) => console.log("error", error));
Wrap the common code in a function passing in the form data and url via variables
const sendFormData = (url, formData) => {
var requestOptions = {
method: "POST",
body: formData,
redirect: "follow",
};
fetch(
url,
requestOptions
)
.then((response) => response.json())
.then((stockData) => console.log('aasfs', stockData))
.catch((error) => console.log("error", error));
}
var formdata1 = new FormData();
formdata.append("market", "KSE100");
sendFormData("api_url here_1", formdata1);
var formdata2 = new FormData();
formdata.append("symbol", "SYS");
sendFormData("api_url here_2", formdata2);
You can define a function like this
const postData = (url, data) => {
const formdata = new FormData();
Object.entries(data).forEach(([k, v]) => {
formdata.append(k, v);
}
var requestOptions = {
method: "POST",
body: formdata,
redirect: "follow",
};
return fetch(
url,
requestOptions
)
.then((response) => response.json())
.then((stockData) => console.log('aasfs',stockData ))
.catch((error) => console.log("error", error));
}
I need to have number format passed to JSON and I cannot use input type hidden because it returns string. I have const formDataJsonString = JSON.stringify(plainFormData); to translate form data to JSON (see below)
How do I POST javascript variable from form into JSON with the functions that I added below?
I have written this to convert it into number but have no clue on how to submit the javascript variable to JSON.
<input type="hidden" class="number" name="applicationType" value=3>
$("#form").submit(function(){
var formInfo = document.forms['form'];
var applicationType = parseInt($(".number").val());
});
The desired result in JSON:
applicationType: 3
Instead of:
applicationType: "3"
UPDATE 1:
So I have this to make it into JSON, and then POST it:
//url is the api
async function postFormDataAsJson({ url, formData }) {
const plainFormData = Object.fromEntries(formData.entries());
//put all accountsToLink value into an array
plainFormData["accountsToLink"] = new Array //create array
$("input[name=accountsToLink] ").each(function() {
plainFormData["accountsToLink"].push($(this).val()) //push value in array
});
const formDataJsonString = JSON.stringify(plainFormData);
const fetchOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: formDataJsonString,
};
const response = await fetch(url, fetchOptions);
if (!response.ok) {
const errorMessage = await response.text();
throw new Error(errorMessage);
}
else if (response.ok) {
window.location.href = "confirmation.html";
}
return response.json();
}
async function handleFormSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
const url = form.action;
try {
const formData = new FormData(form);
const responseData = await postFormDataAsJson({ url, formData });
console.log({ responseData });
} catch (error) {
console.error(error);
}
}
const testform = document.getElementById('testform');
testform.addEventListener('submit', handleFormSubmit);
So you failed to mention you do NOT do what you did in the initial post but instead you use formData
You cannot use formData to JSON integers.
You can map a serialized array and stringify that
async function postFormDataAsJson({ url, formData }) {
const formDataJsonString = JSON.stringify(formData);
console.log(url,formDataJsonString)
// ....
}
async function handleFormSubmit(event) {
event.preventDefault();
const form = event.currentTarget;
const url = form.action;
try {
const formData = $(form).serializeArray().map(
item => ({ [item.name]: isNaN(item.value) ? item.value : +item.value})
);
const responseData = await postFormDataAsJson({ url, formData });
} catch (error) {
console.error(error);
}
}
$("#testform").on("submit", handleFormSubmit);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="testform" action="/bla.php">
<input type="hidden" class="number" name="applicationType" value=3>
<input type="submit" />
</form>
ServerSide (app.js):
I get some data from DB and put it in an array
app.post('/sendform', (req,res) =>{
var array = [{"h":"1"},{"e","2"}];
res.send(array);
)}
ClientSide (client.js):
I want to get that array and add it to my index.html
function tableContent(){
fetch('/')
.then(res => {
console.log(res);
if(res.ok) return res.json();
});
.then(data => {
//do something with html file
});
}
var URL = “127.0.0.1:3000/sendform”;
var req = new Request(URL, {method: 'POST', cache: 'reload'});
fetch(req).then(function(response) {
var reader = response.body.getReader();
return reader.read();
}).then(function(result, done) {
if (!done) {
// do something with each chunk
}
});
The POST method requests your address