Drag and Drop jQuery Ajax Upload - php

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', ...});

Related

Issue with sending a .csv file through ajax to PHP file

I was wondering how I could go about sending a .csv file from a file input container in HTML to another .php file in ajax.
Here's my code:
$(document).ready(function () {
$(".Rsubmit").click(function () {
?????What would I declare to contain the .csv file?
var checkurl = './CSVRemove/getAccountsCSV.php';
runCSVcheck(checkurl);
});
});
function runCSVcheck(checkurl)
{
$.ajax({
type: "POST",
//dataType: "json",
url: checkurl,
data:
{
???? what would I put here?
},
success: function(response) {
code....
});
}
HTML:
Input boxes.....
<span>Enter .csv File: </span><input type="file" name="file" value="" />
Please let me know if there is a solution!
David
If you're planning on sending a file upload via Ajax, I suggest using a jQuery form plugin that support file uploads.
There are a number of them available, but I've had good success with this one: http://www.malsup.com/jquery/form/
It allows you to post a form via Ajax, even if the form includes file upload fields. PHP will receive the form post exactly as it would have done normally if it had been posted via a regular form submit.
Alternatively, you could use HTML5's file API, but only if you don't need to support older browsers like IE8. The jQuery form plugin is probably the safer way to go for now.
hope that helps.

Drag & Drop File Upload

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...

How to upload files using JQuery Ajax [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
File Upload via AJAX within JQuery
How to easily upload files without form submission (with jQuery + AJAX)
I know for a fact that we can upload files using forms with enctype="multipart/form-data" but what i'm trying to figure out is upload files using Jquery Ajax..
Any tips?? Thanks in advance.
Try this jQuery plugin http://valums.com/ajax-upload/
Then use this javascript code
var uploader = new qq.FileUploader({
// pass the element
element: $(selector)[0],
// path to server-side upload script
action: '/server/upload'
});
For more info check the documentation
I have used http://blueimp.github.com/jQuery-File-Upload/ in the past and it comes up with great demo(s) and documentation.
Check it out on https://github.com/blueimp/jQuery-File-Upload
depends on your needs.
for single file,http://valums.com/ajax-upload/ is good enought
for multipla files upload + multi file selects you will need other technologies like flash or html5, you can check plupload or Uploadify
plupload supports flash, html5, silvernight html4 upload methods. and also support multi files select (except for html4)
uploadify supports flash and html5 for multi file selects
The mentioned plugins are all useful but if you would like to know the logic behind the process its something like this:
Create a php file that handles uploading files and can return errors (echo).
Create an HTML page with your form and everything
Create a jquery function to :
Avoid the form from being submitted
create an ajax request to your php file you created in the first step
show the result from the php file in a div.
You need to use FormData object, but it will work only in newer browsers.
if (window.FormData) {
$('input[type=file]').change(function() {
var formdata = new FormData();
var file = this.files[0];
formdata.append("files[]", file);
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false
});
});
}
Some more info: https://developer.mozilla.org/en/XMLHttpRequest/FormData
You can also see lib with example HTML and some additional features: http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/
For supporting older browsers, you can make iframe, clone file input element to the iframe and submit form there. In this way, page will not refresh and it will be AJAX-like.

Using JQuery.Ajax to change content in other file

I am using an iFrame in my application that lets user to upload a CSV file which has information about the new countries to be added into database. What I want is as soon as the CSV file is processed into the database the existing select box that shows current countries from the database should get updated with newly added entries of CSV file.
I am the making ajax call like
$(document).ready(function(){
jQuery.ajax({
type: "POST",
url: "get_all_countries.php",
data: '',
cache: false,
success: function(response)
{
$("#all_countries_select_box").html("<select name='all_countries' id='all_countries' MULTIPLE size='8' style='min-width:250px;'>"+response+"</select>");
}
});
});
My only problem is the id 'all_countries_select_box' is in another PHP file called 'manage_countries.php'. Is there a way to change content of that file from the file that is in iFrame (upload.php). If not, what could be the best possible solution
If you want to access the parent window from inside an iframe you should use window.parent
success: function(response)
{
var parentJQuery = window.parent.jQuery;
parentJQuery("#all_countries_select_box").html("<select name='all_countries' id='all_countries' MULTIPLE size='8' style='min-width:250px;'>"+response+"</select>");
}
if the file you wantr to modify instead is inside an iframe you should do
success: function(response)
{
$('#idoftheiframe').contains().find("#all_countries_select_box").html("<select name='all_countries' id='all_countries' MULTIPLE size='8' style='min-width:250px;'>"+response+"</select>");
}

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