I want to upload an array of files, send it to javascript formData object and then via ajax to some php script which will put the file into database. It works fine when I upload one file, send it to formData object in javascript and send it to php.
Problem is when I send an array of files via formData object, my php script will insert an empty file into database (BLOB - 0B). What do I do wrong?
Example:
<form method="post" action="javascript:sendPHP()" enctype="multipart/form-data">
<input type="file" onchange = 'handleFiles(this.files)' name="pics[]" />
<input type="file" onchange = 'handleFiles(this.files)' name="pics[]" />
<input type="file" onchange = 'handleFiles(this.files)' name="pics[]" />
<input type="submit" value="Upload" />
//Javascript
var formData = new FormData();
function handleFiles(files) {
var file = files[0];
formData.append('pics[]', file, file.name);
}
function sendPHP() {
$.ajax({
type: "POST",
url: "../php/haus.php",
data: formData,
processData: false,
contentType: false,
success: function(data){}
})}
//php
if(strtolower($_SERVER['REQUEST_METHOD']) == 'post' && !empty($_FILES))
{
foreach($_FILES['pics']['tmp_name'] as $index => $tmpName )
{
if(!empty($tmpName) && is_uploaded_file($tmpName))
{
$imgData= addslashes(file_get_contents($_FILES['pics']['tmp_name']));
$resultPics = $dbConnection->query("INSERT INTO picture (pic, text, id) VALUES ('".$imgData."', 'Hi','1')");
}
}
}
You are missing this attribute multiple="multiple" in your <input>
Do it this way ,
<input type="file" onchange = 'handleFiles(this.files)' name="pics[]" multiple="multiple" />
This function handles only single file upload
function handleFiles(files) {
var file = files[0];
formData.append('pics[]', file, file.name);
}
For multiple uploads you need to use a loop inside to append to each file.
Something Like this ,
function handleFiles(files) {
for(var file in files)
{
formData.append('pics[]', file, file.name);
}
The PHP part , you need to use a loop there as well to loop through each file and use json_encode() to convert the array of files into json string , so that you can insert the record as a string in the database and use json_decode() when retrieving the data back from DB.
Hope this helps.
Related
I have this html form which let user upload a file and also another extra input type for extra info about this upload.
<form method="post" enctype="multipart/form-data">
<input id="files" name="files" type="file" size="1" />
<input type="text" id="tags">
<button type="submit" id="btnSave" onchange="uploadFiles();">Upload and Save</button>
</form>
and this is my javascript
function uploadFiles() {
var input = document.getElementById('files');
var files = input.files;
var formData = new FormData();
for (var i = 0; i != files.length; i++) {
formData.append("files", files[i]);
}
$.ajax(
{
url: "https://localhost:xxx/api/file/upload",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function () {
alert("Files Uploaded!");
}
}
);
}
My question is how do I add others parameters (i.e tags here) to post to web api and at the same time upload the file? Post the request at complex type? Any example for complex type which include file upload?
You just can append new properties there.
formdata append will help you to add string and file
formData.append("tags",document.getelementbyid('tags').value);
this is some source to read about FormData
https://developer.mozilla.org/en-US/docs/Web/API/FormData
I am trying to make a form where there will be user data(name,dob etc) and an image. When user submits the form a pdf will be generated with the user given data and the image. I can successfully serialize the data but failed to get image in my pdf. I am using simple ajax post method to post data. Below is my code.
HTML code
<form onsubmit="submitMe(event)" method="POST" id="cform">
<input type="text" name="name" placeholder="Your Name" required>
<input type="file" name="pic" id="pic" accept="image/*" onchange="ValidateInput(this);" required>
<input type="submit" value="Preview"/>
</form>
Jquery code
function submitMe(event) {
event.preventDefault();
jQuery(function($)
{
var query = $('#cform').serialize();
var url = 'ajax_form.php';
$.post(url, query, function () {
$('#ifr').attr('src',"http://docs.google.com/gview?url=http://someurl/temp.pdf&embedded=true");
});
});
}
PHP code
<?php
$name=$_POST['name'];
$image1=$_FILES['pic']['name'];
?>
Here I am not getting image1 value. I want to get the url of the image.
You need FormData to achieve it.
SOURCE
Additionally, you need to change some stuff inside ajax call(explained in link above)
contentType: false
cache: false
processData:false
So the full call would be:
$(document).on('change','.pic-upload',uploadProfilePic);
#.pic-upload is input type=file
function uploadProfilePic(e){
var newpic = e.target.files;
var actual = new FormData();
actual.append('file', newpic[0]);
var newpic = e.target.files;
var actual = new FormData();
actual.append('file', newpic[0]);
$.ajax({
type:"POST",
url:"uploadpic.php",
data: actual,
contentType: false,
cache: false,
processData:false,
dataType:"json",
success: function (response){
#Maybe return link to new image on successful call
}
});
}
Then in PHP you handle it like this:
$_FILES['file']['name']
since you named it 'file' here:
actual.append('file', newpic[0]);
I have a form with input field like some textfields ,textareas,dropdowns and a file upload field which the user will upload while filling the form i want to send form contents (both form field values + uploaded file) as one file to the server below is a very simplified version of my problem .Say i have the following markup
<form id="myForm" method="post" action="something">
<input type="text" name="username" id="username">
<input type="text" name="email" id="email">
<input type="file" name="myFile" id="myFile">
</form>
So now what i want is instead of sending above 2 text fields and a file separately i want them to get embedded in a file and then get sent as a whole.
example
Note that the server where i am sending is third party and only excepts files also file format is proprietary but nonetheless it still a ASCII plain/text.I realize that it's only possible by AJAX and fileReader API so here is what i have tried
var file;
$('#myFile').change(function(e){
file = this.files[0];
var fr = new FileReader();
fr.onload = function(event){
fileData = fr.result;
};
fr.readAsDataURL(file);
$('#myForm').submit(function(e){
e.preventDefault();//prevent submit
var myFile= [$('#username').val(),$('#email').val(),fileData];
$.ajax({
url : "some url",
type: "POST",
contentType:false,
processData:false,
data: myFile;
success:function(data){ }
});
});
Issue is that upon form submission no file gets sent .Any help would be greatly appreciated , thanks.
In form submit you can do as mentioned below for send file with AJAX request
$('#myform').submit(function(e){
e.preventDefault();//prevent submit
var form_data = new FormData();
form_data.append('file', $('#myfile').prop('files')[0]);
form_data.append('username', $("#username").val());
form_data.append('phone', $("#phone").val());
$.ajax({
url : "some url",
type: "POST",
contentType:false,
processData:false,
data: form_data;
success:function(data){ }
});
});
There are 2 parts
Convert file to string format or serialize it on client side using FileReader API
Combine your form values with this string and send them as a file.
Part one
I don't know if you have noticed or not but when you use readAsDataURL() you don't get the original file byte-stream but its base64 encoded version so keeping that in mind change you code to
var fileData;
$('#myFile').change(function(e){
file = this.files[0];
var fr = new FileReader();
fr.onload = function(event) {
encfileData = fr.result;
startInx = encfileData.indexOf('base64');
startInx += 7;
tmp = encfileData.substr(startInx);
//removes the file MIME header part ie. "data:text/plain;base64," before decoding
//regex may be preferable
fileData = atob(tmp); //DECODE
};
fr.readAsDataURL(file);
});
So now you have a string containing your file's byte-stream now as you have said there is some format so depending on that you do whatever manipulation you may need to make it align with the format, since you have mentioned it's plain text format so basic string function are sufficient here.For next part i assume simple colon based CSV format key1:value1,key2:value2
Part Two
Now to truly create a file out of thin air you can use either File or Blob but i would suggest using Blob due to its better support.To contain the file you require FormData simply append your blob to it and send
$('#myForm').submit(function(e){
e.preventDefault();
var txtData = "\n username:"+$("#username").val()+","+"email:"+$("#email").val();
// NOTE: windows uses \r\n instead of \n for newlines
var payLoad = fileData + txtData; //append text field data to the file data
var blob = new Blob([payLoad], {type : 'plain/txt'});
var form = new FormData();
var fileName = 'combined.txt'; //filename that will be used on server
form.append('something', blob, fileName);
$.ajax({
url: "some url",
type: "POST",
cache: false,
contentType: false,
processData: false,
data: form,
success: function(response){alert(response);}
});
});
If using php on linux your $_FILES should look something like this
Array
(
[something] => Array
(
[name] => combined.txt
[type] => plain/txt
[tmp_name] => /tmp/phpJvSJ94
[error] => 0
[size] => 95
)
)
It seems that you're passing sending the wrong variable in your AJAX payload - shouldn't you be sending fileData instead of file?
You can upload data and files:
HTML
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="username" id="username">
<input type="text" name="email" id="email">
<input type="file" name="myFile" id="myFile">
</form>
Jquery
$("form#data").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'your_url',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
I am doing form serialization to send the file name to the server.
This serialization values is empty . I am expecting the file name over here.
My form is having a html file upload element. Which shows the file name in the right side when you select the file.
HTML:
<form name="MyForm" id="MyForm" method="post" action=cgi_path">
<input type="file" name="filename" id="my_file">
</form>
SCRIPT:
var frm_data = $("#MyForm").serialize(); // This is empty
$.ajax(
{
type: "POST",
url: "file upload cgi url",
data: frm_data
});
How to take the file name with out serializing this form?
Is there any problem with form serialization for file name?
Thanks
Files can only be uploaded with AJAX by using FormData, not serialisation (since you are sending more than just the filename).
$.ajax({
url: url,
data: new FormData($("#MyForm").get(0)),
processData: false,
contentType: false,
type: 'POST'
})
I assume you have an <input id="some_ID" name="some_name" type="file" />
so, you just need to pick the element "content"
var file = {}
$('#some_ID').change(function(){
file.content = this.files[0];
file.name = file.name;
file.size = file.size;
file.type = file.type;
});
then you just need to post it to the server.
You don't have to serialize the form to get the file name. To retrieve it just call
var filename = document.getElementById("my_file").files[0];
or this with jQuery
var filename = $('#my_file')[0].files[0]
function chkFile(file1) {
var file = file1.files[0];
var formData = new FormData();
formData.append('formData', file);
$.ajax({
type: "POST",
url: "chkFileType.php",
contentType: false,
processData: false,
data: formData,
success: function (data) {
alert(data);
}
});
}
<form action="" method="post" name="myForm" id="myForm" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
Upload Files
<input type="file" name="uploadFile" id="uploadFile" onChange="chkFile(this)"/>
<input type="submit" name="submitbutt" value="Checkout">
chkFileType.php
<?php
print_r($_FILE)
?>
I want to create a form that when the user uploads a file, it will do a check on the uploaded file before submitting the whole form. I use onChange when a file is uploaded and then pass the formData value to Ajax to call my chkFileType.php to do the checks and alert back the response.
The function is running without any errors, but no response from alert(data);
I know I am doing something wrong, but have no idea which direction to go from. Am I doing the right way?
Everything looks fine. You have done in right way. But to get any response from an ajax call, you have to print the required stuff in chkFileType.php.
Like,
if($ext =="jpg" || $ext == "png"){
echo "Image"; // data in alert will alert as Image
} else if(check for txt file){
echo "Text File"; // data in alert will alert as Text File
} else if(chck for pdf) {
echo "Pdf";// data in alert will alert as Pdf
}
EDIT
change this
var formData = new FormData( $("#formID")[0] );
Hope you understand what i meant to say.
I think the problem is in that you have written "type" instead of "method", "POST" is a method not a type.