pdf file upload ajax html - javascript

var file = $('#image').prop('files')[0];
var filename = $('#af_rpta_propertyland_filename').val();
var form_data = new FormData();
form_data.append('file', file);
alert(form_data);
$.ajax({
type: 'POST',
url: '../include/upload.php',
//dataType: "json",
data: {
file: form_data,
filename: filename
},
success: function(data) {
console.log(data);
for (var i = 0; i < data.length; i++) {
console.log("file " + i + ": " + data[i].file);
}
},
error: function(data) {
alert('No Record Found: ' + data);
}
});
<input id="image" name="image" type="file" />
This how i upload my pdf file using ajax in my php code i do it like this
$file = mysql_real_escape_string($_POST['file']);
$filename = mysql_real_escape_string($_POST['filename']);
if (isset($_FILES['file']) && $_FILES['file']['size'] > 0) {
$tmpName = $_FILES['file']['tmp_name'];
$filetype = $_FILES['file']['type'];
$fp = fopen($tmpName, 'rb'); // read binary
$upload[] = array('filename' => $filename,'file' => $fp);
}
echo json_encode($upload, JSON_UNESCAPED_UNICODE);
From my input(type file) how can i place the value(the pdf file) in to data(in ajax) and from data(ajax) how can i pass it to php file so that i can check if the $_files is not empty

Try creating a json object from files[0] properties , converting file to base64 string
js
$("#image").on("change", function(e) {
var name = $("#af_rpta_propertyland_filename").val()
, file = e.target.files[0]
, filename = name.length > 1 ? name + ".pdf" : file.name
, filetype = file.type
, filesize = file.size
, data = {
"filename":filename,
"filetype":filetype,
"filesize":filesize
}
, reader = new FileReader();
reader.onload = function(e) {
data.file_base64 = e.target.result.split(/,/)[1];
$.post("fileupload.php", {file:data}, "json")
.then(function(data) {
// parse `json` string `data`
var filedata = JSON.parse(data)
// do stuff with `data` (`file`) object
, results = $("<a />", {
"href": "data:" + filedata.filetype
+ ";base64," + filedata.file_base64,
"download": filedata.filename,
"target": "_blank",
"text": filedata.filename
});
$("body").append("<br>download:", results[0]);
}, function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
})
};
reader.readAsDataURL(file)
});
php
<?php
if (isset($_POST["file"])) {
// do php stuff
// call `json_encode` on `file` object
$file = json_encode($_POST["file"]);
// return `file` as `json` string
echo $file;
};
jsfiddle http://jsfiddle.net/guest271314/LL95z474/

Use jQuery version "jquery-1.10.2.min.js"
Use this AJAX
$.ajax({
url: "YourPage.php",
type: "POST",
data: new FormData('YourFormId'),
contentType: false,
processData:false,
success: function(data)
{
// Do your Stuff
}
});
At PHP page just simply use this line
$name = $_FILES['file']['name'];
In this code i have used two new events
contentType
processData
This is necessary to use these to upload and access all data in AJAX.
Hope this will help you.

Related

How to upload more than one file with jQuery and AJAX? [duplicate]

I have designed a simple form which allows the user to upload files to the server. Initially the form contains one 'browse' button. If the user wants to upload multiple files, he needs to click on the "Add More Files" button which adds another 'browse' button in the form. When the form is submitted, the file upload process is handled in 'upload.php' file. It works perfectly fine for uploading multiple files. Now I need to submit the form by using jQuery's '.submit()' and send a ajax ['.ajax()'] request to the 'upload.php' file to handle the file upload.
Here is my HTML form :
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" id="upload" value="Upload File" />
</form>
Here is the JavaScript :
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file' />");
});
});
Here is the code for processing file upload :
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
Any suggestions on how I should write my '.submit()' function will be really helpful.
Finally I have found the solution by using the following code:
$('body').on('click', '#upload', function(e){
e.preventDefault();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success: function (data) {
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
return false;
});
HTML
<form enctype="multipart/form-data" action="upload.php" method="post">
<input name="file[]" type="file" />
<button class="add_more">Add More Files</button>
<input type="button" value="Upload File" id="upload"/>
</form>
Javascript
$(document).ready(function(){
$('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='file[]' type='file'/>");
});
});
for ajax upload
$('#upload').click(function() {
var filedata = document.getElementsByName("file"),
formdata = false;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = filedata.files.length, img, reader, file;
for (; i < len; i++) {
file = filedata.files[i];
if (window.FileReader) {
reader = new FileReader();
reader.onloadend = function(e) {
showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("file", file);
}
}
if (formdata) {
$.ajax({
url: "/path to upload/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(res) {
},
error: function(res) {
}
});
}
});
PHP
for($i=0; $i<count($_FILES['file']['name']); $i++){
$target_path = "uploads/";
$ext = explode('.', basename( $_FILES['file']['name'][$i]));
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];
if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
echo "The file has been uploaded successfully <br />";
} else{
echo "There was an error uploading the file, please try again! <br />";
}
}
/**
Edit: $target_path variable need to be reinitialized and should
be inside for loop to avoid appending previous file name to new one.
*/
Please use the script above script for ajax upload. It will work
Using this source code you can upload multiple file like google one by
one through ajax. Also you can see the uploading progress
HTML
<input type="file" id="multiupload" name="uploadFiledd[]" multiple >
<button type="button" id="upcvr" class="btn btn-primary">Start Upload</button>
<div id="uploadsts"></div>
Javascript
<script>
function uploadajax(ttl,cl){
var fileList = $('#multiupload').prop("files");
$('#prog'+cl).removeClass('loading-prep').addClass('upload-image');
var form_data = "";
form_data = new FormData();
form_data.append("upload_image", fileList[cl]);
var request = $.ajax({
url: "upload.php",
cache: false,
contentType: false,
processData: false,
async: true,
data: form_data,
type: 'POST',
xhr: function() {
var xhr = $.ajaxSettings.xhr();
if(xhr.upload){
xhr.upload.addEventListener('progress', function(event){
var percent = 0;
if (event.lengthComputable) {
percent = Math.ceil(event.loaded / event.total * 100);
}
$('#prog'+cl).text(percent+'%')
}, false);
}
return xhr;
},
success: function (res, status) {
if (status == 'success') {
percent = 0;
$('#prog' + cl).text('');
$('#prog' + cl).text('--Success: ');
if (cl < ttl) {
uploadajax(ttl, cl + 1);
} else {
alert('Done');
}
}
},
fail: function (res) {
alert('Failed');
}
})
}
$('#upcvr').click(function(){
var fileList = $('#multiupload').prop("files");
$('#uploadsts').html('');
var i;
for ( i = 0; i < fileList.length; i++) {
$('#uploadsts').append('<p class="upload-page">'+fileList[i].name+'<span class="loading-prep" id="prog'+i+'"></span></p>');
if(i == fileList.length-1){
uploadajax(fileList.length-1,0);
}
}
});
</script>
PHP
upload.php
move_uploaded_file($_FILES["upload_image"]["tmp_name"],$_FILES["upload_image"]["name"]);
My solution
Assuming that form id = "my_form_id"
It detects the form method and form action from HTML
jQuery code
$('#my_form_id').on('submit', function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
var msg_error = 'An error has occured. Please try again later.';
var msg_timeout = 'The server is not responding';
var message = '';
var form = $('#my_form_id');
$.ajax({
data: formData,
async: false,
cache: false,
processData: false,
contentType: false,
url: form.attr('action'),
type: form.attr('method'),
error: function(xhr, status, error) {
if (status==="timeout") {
alert(msg_timeout);
} else {
alert(msg_error);
}
},
success: function(response) {
alert(response);
},
timeout: 7000
});
});

How to handle multiple file upload using same js function - jquery

Need to make the file upload function upload multiple files at a go. The file upload works fine if uploading just ONE file at a time and upload is done in chunk...
Right now, there is need to expand the form capability to allow multiple file fields which allow user to make multiple selection of files and handling this using a loop within the js function. I tried but it isn't working for me. Not been able to get the js function to work with selection of multiple files. When more than one file is uploaded, it conflicts with each other and none of the file get uploaded successfully.
(function($) {
var fileReader = {};
var file = {};
var slice_size = 1000 * 1024;
function triggerUpload(event) {
event.preventDefault();
fileReader = new FileReader();
file = document.querySelector('#my_file_upload').files[0];
fileUploadHandler(0);
}
$('#form_upload_submit').on('click', triggerUpload);
function fileUploadHandler(start) {
var next_slice = start + slice_size + 1;
var blob = file.slice(start, next_slice);
fileReader.onloadend = function(event) {
if (event.target.readyState !== FileReader.DONE) {
return;
}
var form_data = {
file_data: event.target.result,
file: file.name,
file_type: file.type
};
$.ajax({
url: "server_upload.php",
type: 'POST',
dataType: 'json',
cache: false,
data: form_data,
error: function(jqXHR, textStatus, errorThrown) {
alert('Upload failed');
},
success: function(data) {
alert('success : ' + file.name);
var size_done = start + slice_size;
var percent_done = Math.floor((size_done / file.size) * 100);
if (next_slice < file.size) {
$('#progress_display').html(percent_done + '% Uploaded');
fileUploadHandler(next_slice);
} else {
$('#progress_display').html('Upload Completed!');
}
}
});
};
fileReader.readAsDataURL(blob);
}
})(jQuery);
<?php
$upload_dir = '../upl/';
$file_path = $upload_dir . $_POST['file'];
$file_data = decodeFile( $_POST['file_data'] );
file_put_contents( $file_path, $file_data, FILE_APPEND );
function decodeFile($data)
{
$data = explode( ';base64,', $data );
$data = base64_decode( $data[1] );
return $data;
}
?>
Would be pleased to get some help with this. Thanks!

Javascript dataURL POST to PHP not working

I'm trying to post dataURL over to php but with no succsess.
My .js file is as follow.
var dataURL = signaturePad.toDataURL();
alert(dataURL);
$.ajax({
type: "POST",
url: "test.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
alert(o);
});
alert(dataURL) output is as follow;
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhkAAADZCAYAAACNbSIWAAAeW.....
test.php
<?php
if($_POST['imgBase64']) {
$img = $_POST['imgBase64'];
}
else{
$img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAhkAAADZCAYAAACNbSIWAAAeW.....";
}
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//saving
$timestamp = date('YmdHis');
$fileName = ''.$timestamp.'.png';
echo"$fileData";
file_put_contents($fileName, $fileData);
?>
In my php file I have entered the value of my alert for testing purposes. Now my php page is working 100% due to the test and passing no value from my .js function. but with the correct value it's not even posting to my php page, only when I remove all not standard characters from the dataURL then it post but obvious with corrupt data.
To avoid further confusion the following code works 100%, the .js and the php. where var dataURL = signaturePad.toDataURL(); is passed to the function
function postData(data) {
alert(data);
var desired = data.replace(/[^\w\s]/gi, '');
$.ajax({
type: "POST",
url: "test.php",
data: {
imgBase64: desired
}
}).done(function(o) {
console.log('saved');
alert(o);
});
}
So the problem is the .js will not post with the given dataUrl due to special characters, but I cant remove them.. I even tried var desired = encodeURIComponent(data); witch I can at least decode on the php page but this also does not want to post.
data: {
imgBase64: data
//send key is imgBase64 and data value is undefined in given scope
//replace data with dataURL
}
And in php file change this $_POST['image'] to $_POST['imgBase64']
Thanks for the replies..
I ended up creating a blob first and posting the blob.
function dataURLToBlob(dataURL) {
var parts = dataURL.split(';base64,');
var contentType = parts[0].split(":")[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
$.post("test2.php",
{
name: uInt8Array
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
}

How to reload a img attr "src" after ajax call without knowing the file name from the image tag?

I have this html:
<div class="d-inline-flex">
<img id="reloadIMG" class="p-3 mt-5 imgP" onDragStart="return false" <?php echo htmlentities($avatar, \ENT_QUOTES, 'UTF-8', false); ?>>
<input type="file" id="uploadAvatar" name="uploadedAvatar">
</div>
the value of $avatar:
$pathFolderAvatar = 'user/'.$folder.'/avatar/*';
$imgUserPastaAvatar = glob($pathFolderAvatar)[0] ?? NULL;
if(file_exists($imgUserPastaAvatar)){
$avatar = 'src='.$siteURL.'/'.$imgUserPastaAvatar;
}else{
$avatar = 'src='.$siteURL.'/img/avatar/'.$imgPF.'.jpg';
}
and the script to send a ajax call to my file that process the file upload request:
$(function () {
var form;
$('#uploadAvatar').change(function (event) {
form = new FormData();
form.append('uploadedAvatar', event.target.files[0]);
});
$("#uploadAvatar").change(function() {
$("#loadingIMG").show();
var imgEditATTR = $("div.imgP").next().attr("src");
var imgEdit = $("div.imgP").next();
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime());
}
});
});
});
i tried to force the browser to reload the img on success ajax call $(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime()); but the selector from the var imgEdit and imgEditATTR is not working:
console.log(imgEdit); result: w.fn.init [prevObject: w.fn.init(0)]
console.log(imgEdit); result: undefined;
Why is it happening, and how to fix?
I know that there's a bunch of questions about reload img, but on these questions there's not a method to reload a image without knowing the file name. I checked so many questions and this is what the answears say:
d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());
On my case i don't know the file name, because it's generated randomly on profileForm.php with mt_rand():
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
You can return file name in response to your AJAX request and use it in success block to update src attribute of img tag
So your profileForm.php will look something like
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000).'_'.time();
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'.'.$extension;
//example of the result: 9081341_1546973622.jpg
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo $newname // you can also send a JSON object here
// this can be either echo or return depending on how you call the function
and your AJAX code will look like
$.ajax({
url: 'http://example/test/profileForm.php',
data: form,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data);
}
});
Let profileForm.php return the generated filename:
$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
echo json_encode(['filename' => $folderPFFetchFILE]);
Then in the callback of your POST request:
success: function (data) {
$("#loadingIMG").hide();
$(imgEdit).attr('src', data.filename);
}

Problem with uploading a image via Ajax Call in php?

I want to upload an image via Ajax call but I am not able to upload the image. Kindly check my code what I am doing wrong:
HTML File:
<input class="form-control" type="file" name="photo1" id="photo1" accept="image/*" onchange="loadFile2(event)">
<button type="button" class="btn btn-secondary btn-lg btn-block" onclick="createDocsVerify()">Update Details</button>
Ajax Call:
<script>
function createDocsVerify () {
var data = {
'photo1' : jQuery('#photo1').val(),
};
//Ajax call Start Here
jQuery.ajax({
url : '/myproject/adminseller/sellerdocsverify.php',
method : 'POST',
data : data,
success : function(data){
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error : function (){alert("Something went wrong.");},
});
}
</script>
Php File: sellerdocsverify.php
if (isset($_POST['photo1'])) {
$photo1 = sanitize($_POST['photo1']);
// var_dump Output: string(20) "C:\fakepath\0553.jpg"
}
$errors = array();
$required = array(
'photo1' => 'Please select Photo 1',
);
// check if all required fileds are fill out
foreach ($required as $field => $display) {
if (empty($_POST[$field]) || $_POST[$field] == '') {
$errors[] = $display.'.';
}
}
$allowed = array('png', 'jpg', 'jpeg', 'gif');
$photoNameArray = array();
$tmpLoc = array();
$uploadPath = array();
**// Here is the problem**
$name1 = $_FILES['photo1']['name']; // Here is the problem
Var_dump($name1); // OUTPUT: NULL
**// Here is the problem**
$nameArray = explode('.',$name1);
$fileName = $nameArray[0];
$fileExt = $nameArray[1];
$mime = $_FILES['photo1']['type'];
$mimeType = $mime[0];
$mimeExt = $mime[1];
$tmpLoc = $_FILES['photo1']['tmp_name'];
$fileSize = $_FILES['photo1']['size'];
$uploadName = md5(microtime().$j).'.'.$fileExt;
$uploadPath = BASEURL.'images/products/'.$uploadName;
if ($mimeType != 'image') {
$errors[] = 'The file must be an image.';
}
if (!empty($errors)) {
echo display_errors($errors);
}else{
echo 'passed';
// upload file and insert into database
if ($photoCount > 0) {
move_uploaded_file($tmpLoc1, $uploadPath1);
}
$insertSql = "INSERT INTO docTable (`photo1`)
VALUES ('$photo1')";
$db->query($insertSql);
$_SESSION['success_flash'] = '<span style="color:#FFFFFF;text-align:center;">Data Saved Successfully!</span>';
}
?>
Kind check my code and suggest what I am doing wrong, am I doing something wrong in Ajax call or in php, I am getting the value in $photo1.
Any idea or suggestion would be welcome.
You need to do some special "things" to upload files via AJAX. You need to create a FormData object and manually add the file data to it, and also set the contentType, processData and cache options of your AJAX call to false. Your javascript should look like this:
<script>
function createDocsVerify() {
var formdata = new FormData();
var file = jQuery('#photo1').prop('files')[0];
formdata.append('photo1', file);
//Ajax call Start Here
jQuery.ajax({
url: '/myproject/adminseller/sellerdocsverify.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
if (data != 'passed') {
jQuery('#modal_errors_3').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_3').html("");
location.reload();
}
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
That should upload the photo.

Categories

Resources