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

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!

Related

While uploading multiple input files to the document library, Ajax executes after the loop ends in jQuery

I'm having a problem when using the jQuery .each() and .ajax() functions together when i want to upload all input file to SharePoint document library .
function checkAttachments(NewlyCreatedItemId)
{
$("[type='file']").each(function(){
var FileUploaderID=$(this).attr("id");
var attachfor=$(this).attr("alt");
var file = document.getElementById(FileUploaderID.toString()).files[0];
if (file != undefined) {
uploadDocument(FileUploaderID,attachfor,NewlyCreatedItemId);
}
else {
alert('Please, upload attachments for ');
}
});
}
function uploadDocument(uploader,attachfor,createdID) {
var files = $("#"+uploader+"")[0].files;
if (files.length > 0) {
var fileName = files[0].name;
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var documentLibrary = "ClaimAttachments";
var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary;
// Construct the Endpoint
var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(#target)/Files/add(overwrite=true, url='" + fileName + "')?#target='" + targetUrl + "'&$expand=ListItemAllFields";
uploadFileToFolder(files[0], url, function(data) {
var file = data.d;
var DocFileName = file.Name;
var updateObject = {
__metadata: {
type: file.ListItemAllFields.__metadata.type
},
FileLeafRef: DocFileName , //FileLeafRef --> Internal Name for Name Column
AttachFor : attachfor ,
RequestGUID : createdID
};
alert("File uploaded successfully!");
}, function(data) {
alert("File uploading failed");
});
} else {
alert("Kindly select a file to upload.!");
}
}
function getFileBuffer(uploadFile) {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function(e) {
deferred.resolve(e.target.result);
}
reader.onerror = function(e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(uploadFile);
return deferred.promise();
}
function uploadFileToFolder(fileObj, url, success, failure) {
var apiUrl = url;
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileObj);
// Add the file to the SharePoint folder.
getFile.done(function(arrayBuffer) {
$.ajax({
url: apiUrl,//File Collection Endpoint
type: "POST",
data: arrayBuffer,
processData: false,
async: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
},
success: function(data) {
success(data);
},
error: function(data) {
success(data);
}
});
});
}
it uploads the file of the first file uploader only because when it reach to the ajax call in function (uploadFileToFolder) go to the next iteration, how to can solve it .

Heic to jpg conversion using libheif

I am trying to convert .HEIC image to .JPG using libheif.
libheif converts image on client side browser window only. So in order to save the image i converted image to base64 and then performed ajax to save the image using file_put_contents.
this.canvas.toBlob(function(blob) {
var extension = FILE_EXTENSIONS[blob.type] || ".bin";
var basename = this.filename.replace(/\.[^/.]+$/, "");
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, basename + extension);
return;
}
var readers = new FileReader();
var base64image;
readers.readAsDataURL(blob);
readers.onload = function () {
var base64image = readers.result; // data <-- in this var you have the file data in Base64 format
// console.log(base64image);
// call ajax
var formData = new FormData();
formData.append('filename', basename);
formData.append('avatar', readers.result);
$.ajax('upload.php', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
},
error: function () {
}
});
};
return;
// this.downloads.appendChild(dlink);
// dlink.click();
// URL.revokeObjectURL(url);
}.bind(this), format);
When i convert a single image then it works fine. But if i try to convert in loop it does not works.
Before completing js conversion, my php loop runs (I think this is the issue) So i tried php function sleep() and js set timeout(), But unfortunately none worked.
(function() {
var demo = new HeifDemo(libheif);
<?php $img_array = array('demo/1.heic', 'demo/2.heic', 'demo/3.heic');
foreach ($img_array as $img) : ?>
function saveImage(subject, callback) {
demo.loadUrl(subject);
callback();
}
saveImage('<?php echo $img; ?>', function() {
// demo.saveImage();
setTimeout( function(){
demo.saveImage();
}, 2500 );
});
//});
<?php sleep(4); endforeach; ?> }).call();

Sending multiple images but only one shows

So I am having an issue where I am trying to upload some images after a vehicle was created on my site. I am using Laravel for my site and am using Bootstrap File Input (http://plugins.krajee.com/file-input) to handle the uploading of files but instead of using their built in ajax I am storing the images in a separate form and uploading that form with Ajax. If I check the network tab in chrome dev tools, I can see that multiple images where sent, but I only see one image in my controller.
HTML:
<input id="fileupload" type="file" name="images[]" multiple data-preview-file-type="text"
accepts="image/*" multiple="true" data-browse-on-zone-click="true">
Store Images:
$('#fileupload').on('fileloaded', function (event, file, previewId, index, reader) {
console.log('added image');
imageData.append('images', file);
});
Ajax:
$.ajax({
type: "POST",
url: '{{ route('ajax.newVehicleImageUpload') }}',
data: imageData,
contentType: false,
cache: false,
processData:false,
}).done( function(data) {
console.log(data);
if (data == true) {
toastr.success('Successfully uploaded images.');
}
spinner.hide();
}).fail(function(jqXHR, textStatus) {
spinner.hide();
});
PHP:
if (isset($_FILES['images'])) {
$files = $_FILES['images'];
$count = count((array) $files['name']);
for ($i = 0; $i < $count; $i++) {
$baseFileName = strtolower(str_replace(
' ',
'_',
sprintf('%s-%s-%s-%s-%s-%s.jpg',
trim($request->year),
trim($request->make),
trim(str_replace('-', '_', $request->model)),
trim(Dealer::where('id', '=', \Auth::user()->dealer_id)->first()->cpin),
trim($request->stock_number),
trim(str_random(5)))
));
$location = public_path('images/vehicles/' . $baseFileName);
Image::make(
$files['tmp_name'][$i]
)->resize(
640,
480
)->save(
$location
);
$sequence++;
$newImage = new \App\Vimage();
$newImage->sequence = $sequence;
$newImage->inventory_id = $inventory_id->id;
$newImage->vehicle_id = $request->vehicle_id;
$newImage->dealer_id = \Auth::user()->dealer_id;
$newImage->name = $baseFileName;
$newImage->isStockPhoto = false;
$newImage->isDeleted = false;
$newImage->save();
}
return ('true');
}
Images:
So instead of saving the file, I can save the reader variable which gives me the base64. I can just send that and decode it.
$('#fileupload').on('fileloaded', function (event, file, previewId, index, reader) {
console.log(reader.result);
imageData[] = reader;
});

pdf file upload ajax html

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.

How to get uploaded images from Parse using javascript API

Problem:
I have the Url (eg. http://files.parse.com/../../..jpg ) of the uploaded file and it's fileName, and now need to retrieve the corresponding file from that Url(Parse.com) by using Only via Javascript . Any one have the answer let me know. Thank you very much!
Code: (upload):
function uploadFn(fileName,fileType,fileData,c){
var parseUrl='https://api.parse.com/1/files/'+fileName;
$.ajax({
type:'post',
beforeSend:function(req){
req.setRequestHeader('X-Parse-Application-Id',myParseAppId);
req.setRequestHeader('X-Parse-REST-API-Key',myParseRestApiId);
req.setRequestHeader('Content-Type',fileType); // fileType always == 'image/jpg;'
},
url:parseUrl,
data:fileData,
processData:false,
contentType:false,
success:function(rslt){
if(rslt){
alert('Upload success\n Filename:'+rslt.name+'\n Url:'+rslt.url);
imgObj.save({curUser:curUser,fileName:rslt.name,fileUrl:rslt.url,fileId:c},
{success:function(succ){
alert('File info saved!');
},error:function(err){
alert('Error:'+err.code);
}
}) // save
}
},
error:function(err){
//var errObj=jQuery.parseJSON(err);
alert('Error:'+err.responseText);
}
});
}
upload is not a problem. It works fine! Only for retrieving from Parse.com
(toRetrieve) [I tried as: ]
function fetchImg(url){
$.ajax({
url:url,
async:false,
type:'POST',
beforeSend:function(req){
req.setRequestHeader('X-Parse-Application-Id',myParseAppId);
req.setRequestHeader('X-Parse-REST-API-Key',myParseRestApiId);
req.setRequestHeader('Content-Type','image/jpg');
},
complete:function(rslt){
$('#imgId').attr('src','data:image/jpg;base64,'+rslt.responseText);
},
success:function(){//Success
},
error:function(err){
alert('Error: '+err.responseText+'\nStatus: '+err.statusText);
}
})
}
[output:]
'Error-msg>The specified method not allowed against this resouce' Status: Method Not allowed!.
Notes: ¤ (I saved the fileName, fileUrl to the Parse DataBrowser, and used this for try to retrieve the uploaded file.)
¤ (App is based on 'Phonegap')
¤ Im novice to Parse/Javascript.
Thanks a lot! *
Check here: Load contents of image from camera to a file
basically: with the info in this post. . Big thanks to Raymond Camden!
function gotPic(data) {
window.resolveLocalFileSystemURI(data, function(entry) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var byteArray = new Uint8Array(evt.target.result);
var output = new Array( byteArray.length );
var i = 0;
var n = output.length;
while( i < n ) {
output[i] = byteArray[i];
i++;
}
var parseFile = new Parse.File("mypic.jpg", output);
parseFile.save().then(function(ob) {
navigator.notification.alert("Got it!", null);
console.log(JSON.stringify(ob));
}, function(error) {
console.log("Error");
console.log(error);
});
}
reader.onerror = function(evt) {
console.log('read error');
console.log(JSON.stringify(evt));
}
entry.file(function(s) {
reader.readAsArrayBuffer(s);
}, function(e) {
console.log('ee');
});
});
}
I think to retrieve the image method should be GET instead of POST for your ajax request.

Categories

Resources