Drag & Drop File Upload - php

So I'm struggling a bit to find what I'm looking for and how to implement it.
I have a basic PHP file uploader working, in that a user presses a custom upload button, selects a file and then using JS, it checks for a change (Ie. the user selecting a file) and then submits the form which uploads the image fine.
What I also want now is a drag & drop to upload area. So the user can drag an image from their file explorer and drop it in a designated place (not the whole page) and then once that image has been dropped for the form to submit automatically with their image and use the same PHP processing.
Is this possible and realistic?

This is absolutely realistic and possible without using any third parties plugin.
The following snippets should give you an idea of how it could work:
Drop area
$(".drop-files-container").bind("drop", function(e) {
var files = e.originalEvent.dataTransfer.files;
processFileUpload(files);
// forward the file object to your ajax upload method
return false;
});
the processFileUpload()-Method:
function processFileUpload(droppedFiles) {
// add your files to the regular upload form
var uploadFormData = new FormData($("#yourregularuploadformId")[0]);
if(droppedFiles.length > 0) { // checks if any files were dropped
for(var f = 0; f < droppedFiles.length; f++) { // for-loop for each file dropped
uploadFormData.append("files[]",droppedFiles[f]); // adding every file to the form so you could upload multiple files
}
}
// the final ajax call
$.ajax({
url : "upload.php", // use your target
type : "POST",
data : uploadFormData,
cache : false,
contentType : false,
processData : false,
success : function(ret) {
// callback function
}
});
}
form example
<form enctype="multipart/form-data" id="yourregularuploadformId">
<input type="file" name="files[]" multiple="multiple">
</form>
Feel free to use something like this as a starting point. The browser support of this you can find here http://caniuse.com/#feat=xhr2
Of course you can add any extras you wish like progress bar, preview, animation...

Related

Trying to make andyvr/picEdit plugin upload file via JQUERY post/ajax

I'm using a lightweight image editor jQuery plugin called andyvr/picEdit
https://github.com/andyvr/picEdit
This is just a plugin that turns an input:file element into an HTML canvass, and allows the user to select/edit/crop/manipulate an image file on the client side. The actual uploading and processing is done via the usual FORM UPLOAD and PHP $_FILE processes.
What I wanted to do is grab the "edited" picture data from this plugin and send it via $.post() instead of through the Form submit action.
Do you guys know what element I should select to include in my post variables?
var postvars = {};
postvars.final_image = $("#what_element").val();
$.post("script-name.php", postvars ,function(data){.....
I tried to go through the JS file but I can't seem to figure it out.
PS
I hope I came across clear with this question. I was having a hard time structuring it.
Assuming you are using the same picedit as I used and are still looking for an answer:
The html file input:
<input type='file' name='thefile' id='thebox'>
The jquery to make the file input act like an image edit box:
$(function() {
$('#thebox').picEdit();
});
The post command:
$.post( "handler.php", { story_edited : 1, id : 1 }, function( data ){ document.getElementById( 'photos' ).innerHTML = html = data }, "html" );
Notes:
handler.php = the name of the file that you want to use to process the input!
<div id='photos' name='photos'>
is a standard div tag that I use to update onscreen info in another part of the page! So, document.getElementById( 'photos' ).innerHTML will load handlers.php in to the photos div tag!
Use:
foreach($_FILES as $file)
to process the images as normal file upload from a web page!
I have one other button that pulls it all together. After I finish editing the image, I click on an update button that calls the handler and uploads and saves the file as well as dynamic updating of a photoalbum section elsewhere on the page.
TODO:
If I could find a way to attach a callback function I would not need to use this separate button.

PHP Jquery select multiple file ready to upload

I got a form with file upload fields along with others text field etc., I was thinking to allow user to select their upload files (maximum 3 files), can I achieve it with just share one file input box and display the selected file name under it before submit? can jquery do this? I had found lots of existing jquery library that has such function, but all will uploaded the files in real time before I validate others field and click submit to request ajax process.
Please advise.
I did something like what you maybe need. When you click on the 'select files' and choose some files, it will show you a list of them. I used a jQuery. Here is the code:
<input type="file" id="test" multiple>
<div id="text"></div>
<script type="text/javascript">
$('#test').bind('change', function() {
var files = this.files;
var i = 0;
for(; i < files.length; i++) {
var filename = files[i].name + "<br />";
$("#text").append(filename);
}
});
</script>

Drag and Drop jQuery Ajax Upload

I need to upload files that were added via drag and drop, and to do this I need to use jQUery and Ajax. I have a form where the user can select files via a Browse button, but the user should be able to add files via drag and drop. I do not want to use a plugin.
The Javascript for the drag and drop works, but I don't know how to actually upload the file now (something with FileReader?). Here is the function (with validation code removed) that gets the dropped file.
function handleFileSelect(e) {
e.stopPropagation();
e.preventDefault();
var files = e.dataTransfer.files;
for(var i = 0, f; f = files[i]; i++) {
//i display the file name and do validation here
}
}
I would like to be able to upload the files using jQuery's .ajax from here. Is this possible?
Here is a tutorial how to read the files client side:
Drag and Drop
Here is an example on how to upload the file.
html5-file-upload-jquery-php
Use FormData to upload files via ajax.
var data = new FormData();
...
data.append('file', files[i]);
...
$.ajax({..., data: data, contentType: false, processData: false, type: 'POST', ...});

combining upload picture with registration

i want to make a registration form in which the user should be able to upload the profile picture along with the registration form . I am uploading the picture using ajax like this
$(document).ready(function () {
$('#UploadForm').on('submit', function (e) {
e.preventDefault();
$('#SubmitButton').attr('disabled', ''); // disable upload button
//show uploading message
$("#profile_picture").html('<div class ="update_load" style="padding:10px"><img class="load_pic" src="images/ajax-loader.gif" alt="Please Wait"/> </div>');
$(this).ajaxSubmit({
target: '#profile_picture',
success: afterSuccess //call function after success
});
});
});
the feedback from the ajax is the picture like this
echo '<img class="profile" src="uploads/'.$name.'.'.$ext.'" >';
Now i want to transfer the $name variable on the other process.php file to my current index.php file so that i can insert it using the MySQL Query . i dont know how to do that . And my second question is that if a user changes his picture more than once in the registration form , how would i delete all of his previous uploads ?
ok, this is what I do and I believe that can help you:
1) generate a timestamp + randon number > magic number
2) use uploadify jquery plugin to upload the photo to a temp folder (you can upload photos from the same form where the user completes personal data)
3) save that file with the magic number as the name (you can upload as many as you want over writing the previous one)
4) POST that generated number along with the rest of your form with the user data
choose a number 5):
5a) When saving the data, simply rename the temp file to a final folder with your new id from mysql
5b) leave the temp file as it is, just move it to a final folder and use the magic number to store it in your database
hope this helps!
You can write an afterSuccess function taking response as parameter.
$(this).ajaxSubmit({
target: '#profile_picture',
success: afterSuccess(data) //call function after success
});
function afterSuccess(data)
{
//parse your response to take the name
//make another ajax request to save it to database
}
This function can handle the new picture uploads too.
You will make that checks in php level (the ajax called)
Parse the img string to take src like that:
var img = $('<img class="profile" src="uploads/gaidouri.jpg" />');
var src = $(img).attr('src');

JQuery - Drag n Drop Files - How to get file info?

Interested in building my own drag'n'drop file uploader using JQuery/AJAX/PHP.
Basically I want a file-uploader that users of my site can just drag the file from their computer into a div I created, and it will then upload the file for them to the selected destination.
I would like to build this from scratch, and not use any plugins so that I can better manipulate the restrictions (file types, size, destination folders, etc.)
Have scoured google with no luck, only plugins. Can anyway steer me in the right direction?
UPDATE
Ok, so I figured out how to do what I want. Just set the file input field opacity to 1 so it is hidden, and you can still drag a file into that general area and if you hit the text field it will catch it. HOWEVER, I would like to know how to increase the height/width on the file input field (tried basic css on the file, but it only increases the 'browse' button size and not the actual field where you can drop the file into. Any ideas how to do this?
I basically want a big square div that says 'Drop file here'. So I need to resize the input field.
Just to chime in here, as I've been doing this as well the last couple of days. From what I understand if you're binding the drop event through jQuery you need to access that event.dataTransfer object by going through the event.originalEvent object in the event provided by jQuery.
Example:
In this I bind to both the dragover as well as drop events, as this was necessary to prevent it from performing the default action (found that solution here: Prevent the default action. Working only in chrome )
$('#dropzone').bind('dragover drop', function(event) {
event.stopPropagation();
event.preventDefault();
if (event.type == 'drop') {
console.log(event.originalEvent.dataTransfer.files);
}
});
Also there seems to be a bug where if you console.log() the event.dataTransfer (or event.originalEvent.dataTransfer) it's files array is empty, it's pointed out here: event.dataTransfer.files is empty when ondrop is fired?
To better answer the OPs question (I just noticed the rest of it, and I know it's old but some one might find this helpful):
My implementation is in jQuery, so I hope that's alright:
var files = [];
// Attaches to the dropzone to pickup the files dropped on it. In mine this is a div.
$("#dropzone").bind('dragover drop', function(event) {
// Stop default actions - if you don't it will open the files in the browser
event.stopPropagation();
event.preventDefault();
if (e.type == 'drop') {
files.push(event.originalEvent.dataTransfer.files);
}
});
// Attach this to a an input type file so it can grab files selected by the input
$("#file-input").bind('change', function(event) {
files.push(event.target.files);
});
// This is a link or button which when clicked will do the ajax request
// and upload the files
$("#upload-button").bind('click', function(event) {
// Stop the default actions
event.stopPropagation();
event.preventDefault();
if (files.length == 0) {
// Handle what you want to happen if no files were in the "queue" on clicking upload
return;
}
var formData = new FormData();
$.each(files, function(key, value) {
formData.append(key, value);
});
$.ajax({
url: 'upload-ajax',
type: 'POST',
data: formData,
cache: false,
dataType: 'json',
processData: false, // Don't process the files - I actually got this and the next from an SO post but I don't remember where
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) { /* Handle success */ },
error: function(jqXHR, textStatus, errorThrown) { /* Handle error */ }
});
});
You could also bind to the other events in the accepted answer for doing effects like making the dropzone fade in so you can see it (that's on my todo list for my library). This is the core of the actual ajax file uploading I use, however.
I don't really have a convenient way to test that, but that's in essence how I did it (I essentially took all that code from the library I've been making and adapted it to fit a general code block on here in an easy to understand way). Hopefully this helps some people out. Starting from here it was actually really easy to go ahead and add in a file queue list, with the ability to delete files from the queue, so this should be a pretty good starting point.
You can use the HTML5 dragenter and dragleave events to create a dropzone.
Then by placing a file input inside the dropzone, and hiding it with CSS, you can upload the file when the change event for the input fires, like this
var dropzone = $("#dropzone"),
input = dropzone.find('input');
dropzone.on({
dragenter : dragin,
dragleave : dragout
});
input.on('change', drop);
function dragin(e) { //function for drag into element, just turns the bix X white
$(dropzone).addClass('hover');
}
function dragout(e) { //function for dragging out of element
$(dropzone).removeClass('hover');
}
function drop(e) {
var file = this.files[0];
$('#dropzone').removeClass('hover').addClass('dropped').find('img').remove();
// upload file here
}
FIDDLE
For those interested, I found this tutorial/demo to be helpful: http://www.viget.com/inspire/custom-file-inputs-with-a-bit-of-jquery/
Basically uses a <span> to cover the default input field.

Categories