Dropzone js check for duplicate files using md5_file - javascript

Following is my code which upload files on server using dropzone.js plugin:
var file_up_names = new Array;
var duplicate_files = new Array;
var token = $('input[name=_token]').val();
Dropzone.autoDiscover = false;
var dropzone = $("#addPhotosForm").dropzone({
addRemoveLinks: true,
dictRemoveFileConfirmation: "Do you want to remove this image?",
dictDefaultMessage: "Drop images here to upload",
dictRemoveFile: "Remove photo",
init: function() {
this.on("success", function(file, response) {
if (response.status === 1) {
file_up_names.push(response.filename);
$(file.previewTemplate).append('<span class="server_file_path hide">' + response.newfilename + '</span>');
} else if (response.status === 2) {
duplicate_files.push(response.filename);
this.removeFile(file);
}
}),
this.on("queuecomplete", function() {
var html = "Photos added successfully!";
$('#photoUploadSuccess').html('');
$('#photoUploadError').html('');
$('#photoUploadSuccess').removeClass('hide');
$('#photoUploadError').addClass('hide');
if (file_up_names.length > 0) {
if (duplicate_files.length > 0) {
html += " Following photos are skipped as those are already uploaded.";
html += "<ul>";
for (var i = 0; i < duplicate_files.length; ++i) {
html += "<li>";
html += duplicate_files[i];
html += "</li>";
}
html += "</ul>";
}
$('#photoUploadSuccess').html(html);
} else if (duplicate_files.length > 0 && file_up_names.length === 0) {
html = "Following photos already exists. Please check to see if it already exists and try again.";
html += "<ul>";
for (var i = 0; i < duplicate_files.length; ++i) {
html += "<li>";
html += duplicate_files[i];
html += "</li>";
}
html += "</ul>";
$('#photoUploadSuccess').addClass('hide');
$('#photoUploadError').removeClass('hide');
$('#photoUploadError').html(html);
} else {
html = "Photos not uploaded!";
$('#photoUploadSuccess').addClass('hide');
$('#photoUploadError').removeClass('hide');
$('#photoUploadError').html(html);
}
duplicate_files = [];
file_up_names = [];
setTimeout(function() {
$('#photoUploadSuccess').html('');
$('#photoUploadError').html('');
$('#photoUploadSuccess').addClass('hide');
$('#photoUploadError').addClass('hide');
}, 5000);
}),
this.on("removedfile", function(file) {
var server_file = $(file.previewTemplate).children('.server_file_path').text();
// Do a post request and pass this path and use server-side language to delete the file
var token = $('input[name=_token]').val();
$.ajax({
type: 'POST',
headers: {'X-CSRF-TOKEN': token},
url: "{{ URL::route('removePhotos') }}",
data: "file_name=" + server_file,
dataType: 'html'
});
})
}
});
While below is my server code which get file's md5 and store it on server and next time when user upload same image again it check in database and if same md5_file result found it won't allow to upload image. It work when i use simple form, but on dropzone it's not working:
$tempFile = $_FILES['file']['tmp_name'];
$md5_check = md5_file($tempFile);
//check if same image uploaded before
$duplicateCheck = Photos::where('userId', '=', $this->userId)->where('md5_check', '=', "$md5_check")->where('isDeleted', '=', 0)->count();
I've found that if I upload same images together it won't work and return count 0 from DB. But if I upload same images separately like for example upload image once it uploads, upload same image again it get count from DB and give message that image already there. Maybe it's due to dropzone asynchronous calls but can't figure it out how to handle this.

It's because when you upload more than one image $_FILES contains an array of files, so you should cycle it with a foreach and do your operations inside that loop.
You can check what's happening when you upload more than 1 files by inserting this line of code:
var_dump($_FILES);
Or if you want a result better readable:
echo "<pre>".print_r($_FILES, true)."</pre>";
Check the structure of $_FILES when you upload more than 1 file, it should be an array of files.

Related

Drag and Drop Sortable Image Upload Logic

I am working on web page where I want to use drag an drop image upload system with options for remove and sort images before upload.
I would like to ask you about your opinion if this system logic is good.
I do not know if this system will have some troubles in future bcz all systems which I found have different logic.
My logic:
My system is based mainly on JS and images will be UPLOAD to folder AFTER FORM SUBMIT when whole form (other data about user as name, phone, etc) is filled in. Every modification as remove or change order is done by modify object data via JS.
Web sources:
They are based on UPLOAD images immediately AFTER DROP/SELECT IMAGE and upload to server folder via PHP.
DIFFERENCE: My system no need to send data to PHP every time if one of this actions is happened - new image is added, or deleted or order is changed.
I will be very thankful even if you help me find some other problems. Also I hope it can help someone who is building own system.
Here is my code:
JS:
/* DRAG AND DROP IMG UPLOAD */
// preventing page from redirecting
$("html").on("dragover", function(e) {
e.preventDefault();
e.stopPropagation();
});
$("html").on("drop", function(e) { e.preventDefault(); e.stopPropagation(); });
// Drag enter
$('.add-item__upload-area').on('dragenter', function (e) {
e.stopPropagation();
e.preventDefault();
});
// Drag over
$('.add-item__upload-area').on('dragover', function (e) {
e.stopPropagation();
e.preventDefault();
$('.add-item__dropzone').css({border: '2px dashed #111'});
});
$('.add-item__upload-area').on('dragleave', function (e) {
e.stopPropagation();
e.preventDefault();
$('.add-item__dropzone').css({border: '2px dashed #888'});
});
// Open file browser
$('.add-item__add-photo-btn').click(function() {
$('#input-files').trigger('click'); // execute input type file after click on button
event.preventDefault();
});
// create object to keep img files for modification
var data = {};
// Files added by drop to dropzone area
$('.add-item__upload-area').on('drop', function (e) {
e.stopPropagation();
e.preventDefault();
var totalFiles = e.originalEvent.dataTransfer.files.length;
// fill form by files from input
for (var i = 0; i < totalFiles; i++) {
var file = e.originalEvent.dataTransfer.files[i]; // Get list of the files dropped to area
// fill object for file modifications by img files
data['file_'+i] = file;
// create temp url to img object for creating thumbnail and append img with temp src to thumbnail__wraper div
$('.thumbnail__wrapper').append('<div class="thumbnail" id="file_'+ i +'"><img class="imageThumb" src="' + URL.createObjectURL(file) + '" title="' + file.name + '"/><br/><a class="remove">Zmazať</a></div>');
$('.add-item__add-photo-btn-area').find('p').hide();
}
});
// Files added by selecting in file browser
$('#input-files').on('change', function(){
var totalFiles = $('#input-files')[0].files.length; // get number of uploaded files from input element
// modify ordering of fields inside data object according to order from sortable ui
for (var i = 0; i < totalFiles; i++) {
// By appending [0] to the jQuery object will return the first DOM element. Get <input> element from object.
var file = $('#input-files')[0].files[i]; // Get first file from list of files selected with the <input type="file">
// fill object for file modifications by img files
data['file_'+i] = file;
// create temp url to img object for creating thumbnail and append img with temp src to thumbnail__wraper div
$('.thumbnail__wrapper').append('<div class="thumbnail" id="file_'+ i +'"><img class="imageThumb" src="' + URL.createObjectURL(file) + '" title="' + file.name + '"/><br/><a class="remove">Zmazať</a></div>');
$('.add-item__add-photo-btn-area').find('p').hide();
}
//console.log(data);
//uploadData(formData); // send data via ajax to upload.php
});
// Remove field of data obj after click on remove button
$('.add-item__dropzone').on('click','.remove', function() {
// remove choosen field
delete data[$(this).parent().attr('id')];
$(this).parent('.thumbnail').remove();
//console.log($(this).parent().attr('id'));
//console.log(data);
});
// Make images sortable
$('.thumbnail__wrapper').sortable({
axis: 'x', // axis in which sort is possible
update: function (event, ui) {
// get all ids (item-1, ....) from li elements (setted as sortable) of list in form item[]=1&item[]=2
var reorderList = $(this).sortable('serialize');
//console.log(reorderList);
// fill FormData object by files from data array after order change
var formData = new FormData();
var dataLength = Object.keys(data).length;
//console.log(data);
data = changeOrder(data, reorderList);
//console.log(data);
}
})
// Change order of files inside object data
function changeOrder(obj, order) {
var newObject = {};
// if the g flag is used, all results matching the complete regular expression will be returned, but capturing groups will not.
var matches = order.match(/=/g);
var count = matches.length;
// file[]=1&file[]=0&file[]=2 => ["file[]=1", "file[]=0", "file[]=2"]
var arrayOfOrderValues = order.split('&');
// console.log(arrayOfOrderValues);
for (var i = 0; i < count; i++) {
// get values in appropriate format ["file[]=1", "file[]=0", "file[]=2"] => file_1, file_0, file_2
orderKey = 'file_' + arrayOfOrderValues[i].substring(arrayOfOrderValues[i].lastIndexOf("=") + 1);
// console.log(orderKeyValue);
// check if object contains key(property) as orderKeyValue and then do next step
if(obj.hasOwnProperty(orderKey)) {
// fill value of obj['file_1'] to newObject['file_0'] - ex. in first loop
newObject['file_'+i] = obj[orderKey];
}
}
return newObject;
}
// Sending AJAX request and upload file
function uploadData(formdata){
$.ajax({
url: '_inc/upload.php',
type: 'post',
data: formdata,
contentType: false,
processData: false,
dataType: 'json',
success: function(response){
//addThumbnail(response); // if success - create thumbnail
}
})
}
$('.test').on('submit', function() {
event.preventDefault();
var formData = new FormData(); // Create form
console.log(data);
var count = Object.keys(data).length; // count fields of object
for (var i = 0; i < count; i++) {
formData.append('files[]', data['file_'+i]); // append data to form -> (key, value), file[0] first file from list of files !!! key must have [] for array
}
console.log(count);
uploadData(formData); // send data via ajax to upload.php
})
PHP:
<?php
require($_SERVER['DOCUMENT_ROOT'] . '/bazar/_inc/DBController.php');
// inicialize object
$db_handler = new DBController();
// get total number of files in file list
$total_files = count($_FILES['files']['name']);
// array(5) { ["name"]=> array(2) { [0]=> string(23) "IMG_20190916_105311.jpg" [1]=> string(19) "20180525_115635.jpg" } ["type"]=> array(2) { [0]=> string(10) "image/jpeg" [1]=> string(10) "image/jpeg" } ["tmp_name"]=> array(2) { [0]=> string(28) "/home/gm016900/tmp/phpdU58AU" [1]=> string(28) "/home/gm016900/tmp/phpIqWoaQ" } ["error"]=> array(2) { [0]=> int(0) [1]=> int(0) } ["size"]=> array(2) { [0]=> int(306091) [1]=> int(2315700) } }
// Create array for jQuery information
$return_arr = array();
$images_names = array_filter($_FILES['files']['name']); // filter just values for $key = name
// -> array(2) { [0]=> string(23) "IMG_20190916_105311.jpg" [1]=> string(19) "20180525_115635.jpg" }
//var_dump($images_names);
/* BATCH FILE UPLOAD */
// if $_FILES contains image then do foreach
if ( !empty($images_names) ) {
for($i = 0; $i < $total_files; $i++) {
// Get reference to uploaded image
$image_file = $_FILES["files"];
// Get image name
$image_name = $_FILES["files"]["name"][$i];
// Get file size
$image_size = $_FILES["files"]["size"][$i];
/* BASIC CONTROL */
// Exit if no file uploaded or image name contains unvalid characters /, \\
if ( ( !strpos($image_name, '/') || !strpos($image_name, '\\') ) && isset($image_file) ) {
// define variables if image in correct format is uploaded
$errors = array();
$maxsize = 10485760;
$acceptable = array(
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
} else {
die('No image uploaded.');
}
// Exit if image file is zero bytes or if image size is more then 10 MB
if (getimagesize($image_file["tmp_name"][$i]) <= 0) {
die('Uploaded file has no contents.');
} elseif ($image_size >= $maxsize) {
die('Image is too large. Image must be less than 10 megabytes.');
}
// Determine the type of an image int|false
$image_type = exif_imagetype($image_file["tmp_name"][$i]);
// Exit if is not a valid image file or image has not supported type
if (!$image_type) {
die('Uploaded file is not an image.');
} elseif ( !in_array($image_file["type"][$i], $acceptable) ) {
die('Image has not supported type JPG, PNG, GIF.');
} else {
$src = "default.png";
}
/* CREATE RANDOM IMAGE NAME INSTEDAOF $_FILES['files']['name'] */
// Get file extension based on file type, to prepend a dot we pass true as the second parameter
$image_extension = image_type_to_extension($image_type, true);
// Create a unique image name
$random_image_name = bin2hex(random_bytes(16)) . $image_extension;
/* DEFINE LOCATION */
// 1st create adress with new img random name
$relative_location = "/bazar/assets/img/photos/".$random_image_name;
$absolute_location = dirname(__DIR__, 2).$relative_location;
//var_dump($image_file["tmp_name"][$i]);
//var_dump($absolute_location);
/* MOVE TEMP IMG TO PHOTOS FOLDER */
// 2nd move img with tmp_name to new location under new random name added from 1st step
if (move_uploaded_file($image_file["tmp_name"][$i], $absolute_location)) {
$item_id = 1;
$src = $relative_location;
$query = "INSERT INTO photos (item_id, file_name) VALUES (?, ?)";
$inserted = $db_handler->runQuery( $query, 'is', array($item_id, $src) );
var_dump($inserted);
//$return_arr .= array("name" => $random_image_name,"size" => $image_size, "src"=> $src);
}
}
}
//echo json_encode($return_arr);
Here is code from one Web Source:
$(document).ready(function()
{
$("#drop-area").on('dragenter', function (e){
e.preventDefault();
$(this).css('background', '#BBD5B8');
});
$("#drop-area").on('dragover', function (e){
e.preventDefault();
});
$("#drop-area").on('drop', function (e){
$(this).css('background', '#D8F9D3');
e.preventDefault();
var image = e.originalEvent.dataTransfer.files;
createFormData(image);
});
});
function createFormData(image)
{
var formImage = new FormData();
formImage.append('userImage', image[0]);
uploadFormData(formImage);
}
function uploadFormData(formData)
{
$.ajax({
url: "upload_image.php",
type: "POST",
data: formData,
contentType:false,
cache: false,
processData: false,
success: function(data){
$('#drop-area').html(data);
}});
}

File browsing and omdb

I'm kinda new to php + javascript.
I have set up "cute file browser" to look at a shared folder on my computer.
it works fine displays all files & folders no problem.
Now im trying to use OMDB to search for movie posters and then display them for each movie name.
Currently it works but only with the first movie title. when inspecting the element in FF it does show all the other posters but only within the first
This is the code i made for the OMDB...
var filmName;
var realName;
filmName = finfo;
realName = filmName.split('.')[0];
var omdbUrl = "http://www.omdbapi.com/?t=" + realName;
$.ajax({
url: omdbUrl,
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//now json variable contains data in json format
//let's display a few items
document.getElementById("folders").innerHTML += "<img id='imgposter' class='imgPoster' src='" + json.Poster + "'></img>";
}
});
And this is the code for displaying my movie folders:
if(scannedFolders.length) {
scannedFolders.forEach(function(f) {
var itemsLength = f.items.length,
name = escapeHTML(f.name);
if(itemsLength) {
icon = '<span class="icon folder full"></span>';
}
if(itemsLength == 1) {
itemsLength += ' item';
}
else if(itemsLength > 1) {
itemsLength += ' items';
getPoster(name);
}
else {
itemsLength = 'Empty';
}
var folder = $('<li id="folders" class="folders"><span class="name">' + name + '</span> </li>');
folder.appendTo(fileList);
});
}
This is the error i get
As i said i am new here. if anyone could give me any tips would be great thanks

Is there a way not to let a blob (createObjectURL) show the image which is a GIF file but has a .jpeg extension?

Using blueimp, I'm making a file upload module and I will show an image thumbnail before people upload the image.
My code contains the following:
$('.fileupload').fileupload({
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(jpe?g|png)$/i,
maxNumberOfFiles: 1,
maxFileSize: 3000000,//3MB
loadImageMaxFileSize: 3000000,//3MB
}).on('fileuploadsubmit', function (e, data) {
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('.files');
$.each(data.files, function (index, file) {
// ファイル情報を表示する
var node = $('<p/>')
.append($('<span/>').text(file.name));
// プレビューを表示する
if (!index) {
node.append('<br>');
if((/\.(jpe?g|png)$/i).test(data.files[0].name))
{
node.append('<img class= "uploaded-image" src="'
+ URL.createObjectURL(data.files[0]) + '"/><br>');
}
node.append(uploadButton.clone(true).data(data))
.append(cancelButton);
}
node.appendTo(data.context);
});
}) // .on(... code following
It works well, but if people change a GIF file extension to ".jpeg" and upload it, the blob will also work well to show the GIF and, I think it's not safe. Is there a way not let blob to show the thumbnail In this case?
When submit the file, I'm checking the file in the server side if the file is really an image file (although it has a valid extension).
(this link helped me)
The code below worked well:
if (!index) {
node.append('<br>');
if((/\.(jpe?g|png)$/i).test(data.files[0].name))
{
if (window.FileReader && window.Blob)
{
var blob = data.files[0]; // See step 1 above
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for(var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
if((header == "89504e47") || (header.substr(0,6) == "ffd8ff"))
{
$("button.upload").before('<img class= "uploaded-image" src="' + URL.createObjectURL(data.files[0]) + '"/><br>');
$(".file_upload").attr("style", "height: 600px; overflow-y: auto");
}
else
{
$("button.upload").prop('disabled', true);
var error = $('<span class="text-danger"/>').text(msg[4]);
$('.files').append('<br>').append(error);
}
};
fileReader.readAsArrayBuffer(blob);
}
}
node.append(uploadButton.clone(true).data(data))
.append(cancelButton);
}

How to print all the txt files inside a folder using java script

I need to print all the txt files from a directory inside an HTML using javascript.
i tried to modify a code dealing with photos but I didn't success
How to load all the images from one of my folder into my web page, using Jquery/Javascript
var dir = "D:\Finaltests\test1\new\places";
var fileextension = ".txt";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function (data) {
//List all .txt file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<input type='file' onload='readText(" + dir + ")>");
});
}
});
You can use <input type="file"> with multiple attribute set, accept attribute set to text/plain; change event ;FileReader, for loop.
var pre = document.querySelector("pre");
document.querySelector("input[type=file]")
.addEventListener("change", function(event) {
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
(function(file) {
var reader = new FileReader();
reader.addEventListener("load", function(e) {
pre.textContent += "\n" + e.target.result;
});
reader.readAsText(file)
}(files[i]))
}
})
<input type="file" accept="text/plain" multiple />
<pre>
</pre>
You can also use webkitdirectory and allowdirs attributes for directory upload at chrome, chromium; at nightly 45+ or firefox 42+ where dom.input.dirpicker preference set to true, see Firefox 42 for developers , Select & Drop Files and/or Folders to be parsed. Note, you can also drop folders from file manager at <input type="file"> element
var pre = document.querySelector("pre");
document.querySelector("input[type=file]")
.addEventListener("change", function(event) {
console.log(event.target.files)
var uploadFile = function(file, path) {
// handle file uploading
console.log(file, path);
var reader = new FileReader();
reader.addEventListener("load", function(e) {
pre.textContent += "\n" + e.target.result;
});
reader.readAsText(file)
};
var iterateFilesAndDirs = function(filesAndDirs, path) {
for (var i = 0; i < filesAndDirs.length; i++) {
if (typeof filesAndDirs[i].getFilesAndDirectories === 'function') {
var path = filesAndDirs[i].path;
// this recursion enables deep traversal of directories
filesAndDirs[i].getFilesAndDirectories()
.then(function(subFilesAndDirs) {
// iterate through files and directories in sub-directory
iterateFilesAndDirs(subFilesAndDirs, path);
});
} else {
uploadFile(filesAndDirs[i], path);
}
}
};
if ("getFilesAndDirectories" in event.target) {
event.target.getFilesAndDirectories()
.then(function(filesAndDirs) {
iterateFilesAndDirs(filesAndDirs, '/');
})
} else {
// do webkit stuff
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
(function(file) {
uploadFile(file)
}(files[i]))
}
}
})
<!DOCTYPE html>
<html>
<head>
<script></script>
</head>
<body>
<input type="file" webkitdirectory allowdirs directory />
<pre>
</pre>
</body>
</html>
plnkr http://plnkr.co/edit/Y1XYd9rLOdKRHw6tb1Sh?p=preview
For ajax requests at chromium, chrome file: protocol local filesystem you can launch with --allow-file-access-from-files flag set, see Jquery load() only working in firefox?.
At firefox you can set security.fileuri.strict_origin_policy to false, see Security.fileuri.strict origin policy.
For a possible $.ajax() approach at chrome, chromium you can try
var path = "/path/to/drectory"; // `D:\`, `file:///`
var files = [];
$.ajax({url:path, dataType:"text html"})
.then((data) => {
// match file names from `html` returned by chrome, chromium
// for directory listing of `D:\Finaltests\test1\new\places`;
// you can alternatively load the "Index of" document and retrieve
// `.textContent` from `<a>` elements within `td` at `table` of
// rendered `html`; note, `RegExp` to match file names
// could probably be improved, does not match space characters in file names
var urls = $.unique(data.match(/\b(\w+|\d+)\.txt\b/g));
return $.when.apply($, $.map(urls, (file) => {
files.push(file);
// `\`, or `/`, depending on filesystem type
return $.ajax({url:path + "/" + file
, dataType:"text html"})
.then((data) => {
// return array of objects having property set to `file` name,
// value set to text within `file`
return {[file]:data}
})
}))
})
.then((...res) => {
console.log(res, files)
})
you can't reach the host filesystem with javascript for security reason.
The best you can do is to make a single ajax call to a server-side script (php for exemple) that will collect all html file and return them to your ajax call.
gethtml.php:
<?php
$output = "";
// your list of folders
$folders = [
'D:\Finaltests\test1\new\places1',
'D:\Finaltests\test1\old\places2',
'D:\Finaltests\test1\whatever\places3'
];
foreach ($folders as $key => $dir) {
if(!is_dir($dir))
continue;
// get all files of the directory
$files = scandir($dir);
foreach ($files as $file) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
if(finfo_file($finfo, $file) == 'text/plain')
$output .= file_get_contents($dir . DIRECTORY_SEPARATOR . $file);
}
}
echo $output;
exit;
?>
Ajax call:
$.get('path/to/gethtml.php', function(response){
$('body').html(response);
});
you can change the line of php that check the mime type according to the type of the file you want to get (plain text or text/html or whatever)

PHP AJAX upload is not working correctly with php://input

I am trying to use the JavaScript/jQuery Ajax File Uploader by Jordan Feldstein available at https://github.com/jfeldstein/jQuery.AjaxFileUpload.js
It is an older library but still very popular due to it's simplicity and for being so lightweight (around 100 lines) and you can attach it to a single form input filed and it simply works! You select a file as normal with the form inut filed and on selection it instantly uploads using AJAX and returns the uploaded file URL.
This makes the library good for my use where I am uploading a file inside a modal window which is also generate with AJAX and I have used this library in many similar projects.
My backend is using PHP and Laravel and that is where my issue seems to be.
My test script works but when I implement it into my Laravel app it returns this error....
ERROR: Failed to write data to 1439150550.jpg, check permissions
This error is set in my controller below when this code is not retuning a value...
$result = file_put_contents( $folder . '/' .$filename, file_get_contents('php://input') );
So perhaps this part file_get_contents('php://input') does not contain my file data?
It does create the proper directory structure and even a file which is /uploads/backing/2015/08/1439150550.jpg
The 1439150550.jpg is a timestamp of when the upload took place. It create this file in the proper location however the file created has no content and is 0 bytes!
Below is my Laravel Controller action which handles the back-end upload and below that the JavaScript....
PHP Laravel Controller Method:
public function uploadBackingStageOneFile(){
// Only accept files with these extensions
$whitelist = array('ai', 'psd', 'svg', 'jpg', 'jpeg', 'png', 'gif');
$name = null;
$error = 'No file uploaded.';
$destination = '';
//DIRECTORY_SEPARATOR
$utc_str = gmdate("M d Y H:i:s", time());
$utc = strtotime($utc_str);
$filename = $utc . '.jpg';
$folder = 'uploads/backing/'.date('Y') .'/'.date('m');
//if Directory does not exist, create it
if(! File::isDirectory($folder)){
File::makeDirectory($folder, 0777, true);
}
// Save Image to folder
$result = file_put_contents( $folder . '/' .$filename, file_get_contents('php://input') );
if (!$result) {
Log::info("ERROR: Failed to write data to $filename, check permissions");
return "ERROR: Failed to write data to $filename, check permissions\n";
}
$url = $folder . '/' . $filename;
return Response::json(array(
'name' => $name,
'error' => $error,
'destination' => $url
));
}
JavaScript AJAX FIle Upload LIbrary
/*
// jQuery Ajax File Uploader
//
// #author: Jordan Feldstein <jfeldstein.com>
// https://github.com/jfeldstein/jQuery.AjaxFileUpload.js
// - Ajaxifies an individual <input type="file">
// - Files are sandboxed. Doesn't matter how many, or where they are, on the page.
// - Allows for extra parameters to be included with the file
// - onStart callback can cancel the upload by returning false
Demo HTML upload input
<input id="new-backing-stage-1-file" type="file">
Demo JavaScript to setup/init this lbrary on the upload field
$('#new-backing-stage-1-file').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
*/
(function($) {
$.fn.ajaxfileupload = function(options) {
var settings = {
params: {},
action: '',
onStart: function() { },
onComplete: function(response) { },
onCancel: function() { },
validate_extensions : true,
valid_extensions : ['gif','png','jpg','jpeg'],
submit_button : null
};
var uploading_file = false;
if ( options ) {
$.extend( settings, options );
}
// 'this' is a jQuery collection of one or more (hopefully)
// file elements, but doesn't check for this yet
return this.each(function() {
var $element = $(this);
// Skip elements that are already setup. May replace this
// with uninit() later, to allow updating that settings
if($element.data('ajaxUploader-setup') === true) return;
$element.change(function()
{
// since a new image was selected, reset the marker
uploading_file = false;
// only update the file from here if we haven't assigned a submit button
if (settings.submit_button == null)
{
upload_file();
}
});
if (settings.submit_button == null)
{
// do nothing
} else
{
settings.submit_button.click(function(e)
{
// Prevent non-AJAXy submit
e.preventDefault();
// only attempt to upload file if we're not uploading
if (!uploading_file)
{
upload_file();
}
});
}
var upload_file = function()
{
if($element.val() == '') return settings.onCancel.apply($element, [settings.params]);
// make sure extension is valid
var ext = $element.val().split('.').pop().toLowerCase();
if(true === settings.validate_extensions && $.inArray(ext, settings.valid_extensions) == -1)
{
// Pass back to the user
settings.onComplete.apply($element, [{status: false, message: 'The select file type is invalid. File must be ' + settings.valid_extensions.join(', ') + '.'}, settings.params]);
} else
{
uploading_file = true;
// Creates the form, extra inputs and iframe used to
// submit / upload the file
wrapElement($element);
// Call user-supplied (or default) onStart(), setting
// it's this context to the file DOM element
var ret = settings.onStart.apply($element, [settings.params]);
// let onStart have the option to cancel the upload
if(ret !== false)
{
$element.parent('form').submit(function(e) { e.stopPropagation(); }).submit();
}
}
};
// Mark this element as setup
$element.data('ajaxUploader-setup', true);
/*
// Internal handler that tries to parse the response
// and clean up after ourselves.
*/
var handleResponse = function(loadedFrame, element) {
var response, responseStr = $(loadedFrame).contents().text();
try {
//response = $.parseJSON($.trim(responseStr));
response = JSON.parse(responseStr);
} catch(e) {
response = responseStr;
}
// Tear-down the wrapper form
element.siblings().remove();
element.unwrap();
uploading_file = false;
// Pass back to the user
settings.onComplete.apply(element, [response, settings.params]);
};
/*
// Wraps element in a <form> tag, and inserts hidden inputs for each
// key:value pair in settings.params so they can be sent along with
// the upload. Then, creates an iframe that the whole thing is
// uploaded through.
*/
var wrapElement = function(element) {
// Create an iframe to submit through, using a semi-unique ID
var frame_id = 'ajaxUploader-iframe-' + Math.round(new Date().getTime() / 1000)
$('body').after('<iframe width="0" height="0" style="display:none;" name="'+frame_id+'" id="'+frame_id+'"/>');
$('#'+frame_id).get(0).onload = function() {
handleResponse(this, element);
};
// Wrap it in a form
element.wrap(function() {
return '<form action="' + settings.action + '" method="POST" enctype="multipart/form-data" target="'+frame_id+'" />'
})
// Insert <input type='hidden'>'s for each param
.before(function() {
var key, html = '';
for(key in settings.params) {
var paramVal = settings.params[key];
if (typeof paramVal === 'function') {
paramVal = paramVal();
}
html += '<input type="hidden" name="' + key + '" value="' + paramVal + '" />';
}
return html;
});
}
});
}
})( jQuery );
My JavaScript usage of the above library:
// When Modal is shown, init the AJAX uploader library
$("#orderModal").on('shown.bs.modal', function () {
// upload new backing file
$('#new-backing-stage-1-file').ajaxfileupload({
action: 'http://timeclock.hgjghjg.com/orders/orderboards/order/uploadbackingimage',
params: {
extra: 'info'
},
onComplete: function(response) {
console.log('custom handler for file:');
console.log('got response: ');
console.log(response);
console.log(this);
//alert(JSON.stringify(response));
},
onStart: function() {
//if(weWantedTo) return false; // cancels upload
console.log('starting upload');
console.log(this);
},
onCancel: function() {
console.log('no file selected');
console.log('cancelling: ');
console.log(this);
}
});
});
The problem is like you said, file_get_contents('php://input') does not contain your file data.
jQuery.AjaxFileUpload plugin wrap file input element with a form element that contains enctype="multipart/form-data" attribute. 1
From php documentation: 2
php://input is not available with enctype="multipart/form-data".

Categories