Drag & drop upload after clicking a button

Friends, I have used this wonderful script to upload images, but now I want to customize it to upload only after clicking a button.

By default it uploads automatically.

Can you help?

Hugs.

Are you sure?

The article seems to parse the images straight away but doesn’t do anything with uploading.
Do you have a link to your page?

The upload is done automatically. I gostria to upload only after clicking a button.

You can test on my server: http://blabloo.com.br/upload/

The images are moved to http://blabloo.com.br/upload/uploads

Hugs.

Ah, ok.

All you need to do is remove UploadFile(f); from FileSelectHandler
and add submitbutton.addEventListener(“drop”, UploadFile, false); instead of hiding the submit button.

Friend, did as you suggested and it did not work. See:

function FileSelectHandler(e) {

		// cancel event and hover styling
		FileDragHover(e);

		// fetch FileList object
		var files = e.target.files || e.dataTransfer.files;

		// process all File objects
		for (var i = 0, f; f = files[i]; i++) {
			ParseFile(f);
		}

	}
function Init() {

		var fileselect = $id("fileselect"),
			filedrag = $id("filedrag"),
			submitbutton = $id("submitbutton");

		// file select
		fileselect.addEventListener("change", FileSelectHandler, false);

		// is XHR2 available?
		var xhr = new XMLHttpRequest();
		if (xhr.upload) {

			// file drop
			filedrag.addEventListener("dragover", FileDragHover, false);
			filedrag.addEventListener("dragleave", FileDragHover, false);
			filedrag.addEventListener("drop", FileSelectHandler, false);
			filedrag.style.display = "block";

			submitbutton.addEventListener("drop", UploadFile, false);
		}

	}

Change “drop” to “click” on the submitbutton.addEventListener. Submit buttons do not have a drop event

Still did not work. Do a test: http://blabloo.com.br/upload/. No need to change anything in HTML? Is thus:

<form id="upload" action="upload.php" method="POST" enctype="multipart/form-data">

<fieldset>
<legend>HTML File Upload</legend>

<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="999999999999999999999999999999999999999999999999999999999999999" />
<div>
	<label for="fileselect">Files to upload:</label>
	<input type="file" id="fileselect" name="fileselect[]" multiple="multiple" />
	<div id="filedrag">or drop files here</div>
</div>
<div id="submitbutton">
	<button type="submit">Upload Files</button>
</div>

</fieldset>

</form>

Yep, you need to update the HTML too.

Okay, so the first thing you need to do is put an id attribute on the button. id=“btnSubmit” or something similar should work.

Then change this line

submitbutton.addEventListener("click", UploadFile, false); //was previously using drop

To

$id('btnSubmit').addEventListener("click", UploadFile, false); // needs to match the id attribute you placed on the button

It did not work. It is as if the javascript does not exist. :frowning:

Alright, sorry, I missed a lot in the JavaScript code, as UploadFile requires you to pass in which file to upload.

So you need a new function




	// file selection
	function UploadFiles(e) {

		// fetch FileList object
		var files = e.target.files || e.dataTransfer.files;

		// process all File objects
		for (var i = 0, f; f = files[i]; i++) {
			UploadFile(f);
		}

	}

Then switch the button click event to call UploadFiles instead of UploadFile (I’m not 100% certain this will work either, as I don’t know if the event will contain the target files or not).

Still did not work, but I think it is that way.

Okay, last idea (for now), as I’m doing this without any php server available to me for testing.

Add the following variable to the top of your script (as shown below):

(function() {
  var filesThatWereDropped = new Array();

Update your ParseFile function to the following:

	// output file information
	function ParseFile(file) {

		Output(
			"<p>File information: <strong>" + file.name +
			"</strong> type: <strong>" + file.type +
			"</strong> size: <strong>" + file.size +
			"</strong> bytes</p>"
		);



		// display text
		if (file.type.indexOf("text") == 0) {
			var reader = new FileReader();
			reader.onload = function(e) {
				Output(
					"<p><strong>" + file.name + ":</strong></p><pre>" +
					e.target.result.replace(/</g, "<").replace(/>/g, ">") +
					"</pre>"
				);
			}
			reader.readAsText(file);
                        filesThatWereDropped.push(file);
		}

	}

Update your UploadFiles function to the following:

	function UploadFiles(e) {

		// process all File objects
                while (filesThatWereDropped.length > 0) {
                        var f = filesThatWereDropped.pop();
			UploadFile(f);
		}

	}

It did not work.

I created an FTP user for you and send via private message.

Thanks for the help.

Hey what do you know! I was very close to solving this. Just had the filesThatWereDropped.push in the wrong spot.

Here is the working JavaScript

/*
filedrag.js - HTML5 File Drag & Drop demonstration
Featured on SitePoint.com
Developed by Craig Buckler (@craigbuckler) of OptimalWorks.net
*/
(function() {
	var filesThatWereDropped = new Array();
	
	// getElementById
	function $id(id) {
		return document.getElementById(id);
	}


	// output information
	function Output(msg) {
		var m = $id("messages");
		m.innerHTML = msg + m.innerHTML;
	}


	// file drag hover
	function FileDragHover(e) {
		e.stopPropagation();
		e.preventDefault();
		e.target.className = (e.type == "dragover" ? "hover" : "");
	}


	// file selection
	function FileSelectHandler(e) {

		// cancel event and hover styling
		FileDragHover(e);

		// fetch FileList object
		var files = e.target.files || e.dataTransfer.files;

		// process all File objects
		for (var i = 0, f; f = files[i]; i++) {
			ParseFile(f);
		}

	}
	
	function UploadFiles(e) {

		// process all File objects
		while (filesThatWereDropped.length > 0) {
			var f = filesThatWereDropped.pop();
			UploadFile(f);
		}

	}


	// output file information
	function ParseFile(file) {

		Output(
			"<p>File information: <strong>" + file.name +
			"</strong> type: <strong>" + file.type +
			"</strong> size: <strong>" + file.size +
			"</strong> bytes</p>"
		);



		// display text
		if (file.type.indexOf("text") == 0) {
			var reader = new FileReader();
			reader.onload = function(e) {
				Output(
					"<p><strong>" + file.name + ":</strong></p><pre>" +
					e.target.result.replace(/</g, "<").replace(/>/g, ">") +
					"</pre>"
				);
			}
			reader.readAsText(file);
		}
		
		filesThatWereDropped.push(file);

	}


	// upload JPEG files
	function UploadFile(file) {

		// following line is not necessary: prevents running on SitePoint servers
		if (location.host.indexOf("sitepointstatic") >= 0) return

		var xhr = new XMLHttpRequest();
		if (xhr.upload && file.type == "application/vnd.rn-realmedia-vbr" || file.type == "application/pdf" || file.type == "video/x-ms-wmv" || file.type == "video/x-flv" || file.type == "image/png" || file.type == "image/jpeg" && file.size <= $id("MAX_FILE_SIZE").value) {

			// create progress bar
			var o = $id("progress");
			var progress = o.appendChild(document.createElement("p"));
			progress.appendChild(document.createTextNode("upload " + file.name));


			// progress bar
			xhr.upload.addEventListener("progress", function(e) {
				var pc = parseInt(100 - (e.loaded / e.total * 100));
				progress.style.backgroundPosition = pc + "% 0";
			}, false);

			// file received/failed
			xhr.onreadystatechange = function(e) {
				if (xhr.readyState == 4) {
					progress.className = (xhr.status == 200 ? "success" : "failure");
				}
			};

			// start upload
			xhr.open("POST", $id("upload").action, true);
			xhr.setRequestHeader("X_FILENAME", file.name);
			xhr.send(file);

		}

	}


	// initialize
	function Init() {

		var fileselect = $id("fileselect"),
			filedrag = $id("filedrag"),
			submitbutton = $id("btnSubmit");

		// file select
		fileselect.addEventListener("change", FileSelectHandler, false);

		// is XHR2 available?
		var xhr = new XMLHttpRequest();
		if (xhr.upload) {

			// file drop
			filedrag.addEventListener("dragover", FileDragHover, false);
			filedrag.addEventListener("dragleave", FileDragHover, false);
			filedrag.addEventListener("drop", FileSelectHandler, false);
			filedrag.style.display = "block";

			submitbutton.addEventListener("click", UploadFiles, false);
		}

	}

	// call initialization file
	if (window.File && window.FileList && window.FileReader) {
		Init();
	}


})();

Meant to put this in my first response, but you may want to add


		e.stopPropagation();
		e.preventDefault();

to the UploadFiles function so it doesn’t redirect to upload.php

How strange it did not work. http://blabloo.com.br/upload/

I haven’t uploaded the new JavaScript file to your server (as for some reason, I can access your website). So you will need to update the JavaScript file (I can’t even get to http://blabloo.com.br/)

Everything worked perfectly, except the progress bar that is only satisfied when the upload finishes.

Thank you

Right, that is where you need to add

e.stopPropagation();
		e.preventDefault();

To the UploadFiles(e) function, like so:

	function UploadFiles(e) {

		e.stopPropagation();
		e.preventDefault();
		// process all File objects
		while (filesThatWereDropped.length > 0) {
			var f = filesThatWereDropped.pop();
			UploadFile(f);
		}

	}

This problem is solved, had not seen this piece of code. The problem now is different. :slight_smile: