Enable HTML5 Drag&Drop upload from one window to another using filedrop

It’s the new hype: HTML5 and the new upload files feature. We’ve seen it in WordPress, Google image search, etc. While searching for jQuery plugins that can make my life easier I found jQuery Filedrop. Great plugin, does what it says and it does that good. It works great with files on local computer – but what if you want to drag and drop an image from one page to another without first creating a local copy? Same as seen on Google Images search?

To make drag and drop from one browser window to another work, we need some additional stuff (besides jQuery and Filedrop):

  • Image proxy: PHP script that will convert image at remote URL to DataURL
  • dataURLtoBlob JS function: Function that converts DataURL to Blob. I’ve grabbed Javascript Canvas to Blob that includes this function.
  • Small modification to jQuery filedrop plugin

Please, make sure you’ve managed to make filedrop work with local files. I won’t go into details about that. If you need tutorial about that, check Tutorialzine’s article about it.

First, we need to create a simple PHP script that will act as our image proxy. Script will take an URL and return DataURL from it. The following script is as simple as it can get:

<?php
if (!isset($_GET['u']))
	die("no u");
$url = trim($_GET['u']);

$fp = fopen($url, 'r');
if (!$fp){
	die("!");
}
$meta = stream_get_meta_data($fp);
$srch = 'Content-Type:';
$mime = NULL;
foreach($meta['wrapper_data'] as $str){
	if (strncmp($str, $srch, strlen($srch)) == 0){
		$mime = explode(':', $str);
		$mime = $mime[1];
		$mime = trim($mime);
		break;
	}
}
if ($mime === NULL)
	die("?");
$buf = '';
while (!feof($fp)){
  $buf .= fgets($fp);
}
$buf = base64_encode($buf);
echo "data:$mime;base64,$buf";
?>

Next, we need to modify filedrop a bit, to also check if the dropped item is from another page. I’m using version 0.1.0 and we need to modify the function drop() found on line 83. Basically, we just add the following code after line 85 in original filedrop code:

      if (files === null || files === undefined || files.length === 0) {
		/**
		 * Check if image was dragged onto from another window
		 */
		var url = e.dataTransfer.getData("Text");
		if (url.length > 1){
			$.ajax({
				async: false,
				url: 'PATH_TO_IMAGE_PROXY.PHP?u=' + url,
				error: function(jqXHR, textStatus, errorThrown){
					alert('ERROR: ' + textStatus);
				},
				success: function(data, textStatus, jqXHR){
					var blob = dataURLtoBlob(data);
					blob.name = url.replace(/[^a-zA-Z0-9]+/g, "_");
					files = new Array(blob);
				}
			});
		}
      }

To make things simple, here’s the whole drop() function you can copy&paste:

    function drop(e) {
      opts.drop.call(this, e);
      files = e.dataTransfer.files;
      if (files === null || files === undefined || files.length === 0) {
		/**
		 * Check if image was dragged onto from another window
		 */
		var url = e.dataTransfer.getData("Text");
		if (url.length > 1){
			$.ajax({
				async: false,
				url: 'PATH_TO_IMAGE_PROXY.PHP?u=' + url,
				error: function(jqXHR, textStatus, errorThrown){
					alert('ERROR: ' + textStatus);
				},
				success: function(data, textStatus, jqXHR){
					var blob = dataURLtoBlob(data);
					blob.name = url.replace(/[^a-zA-Z0-9]+/g, "_");
					files = new Array(blob);
				}
			});
		}
      }
	  if (files === null || files === undefined || files.length === 0) {
        opts.error(errors[0]);
        return false; 
	  }
      files_count = files.length;
      upload();
      e.preventDefault();
      return false;
    }

Do not forget to change the PATH_TO_IMAGE_PROXY.PHP! That’s the script we created in first step.

Also, do not forget to include the Javascript Canvas to Blob js file.

Here’s my test page source:

<html>
	<head>
		<title>Test upload</title>
		<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
		<script type="text/javascript" src="/js/jquery.js"></script>
		<script type="text/javascript" src="/js/jquery.filedrop.js"></script>
		<script type="text/javascript" src="/js/cavas-to-blob.js"></script>
		<script type="text/javascript">
		$(function(){	
			$('#dropbox').filedrop({
				url: 'PATH_TO_UPLOAD_HANDLER_SCRIPT.PHP',
				paramname: 'pic', 
				maxfiles: 5,
				maxfilesize: 5,
				uploadFinished:function(i,file,response){
					if (response.error){
						alert("ERROR: " + response.error);
					}
					else {
						alert("File uploaded!");
					}
				},
				allowedfiletypes: ['image/jpg','image/png','image/gif', 'image/jpeg'],
			});
		});
		</script>
	</head>
	<body>
	<div id=dropbox style="width: 400px; height: 200px; background-color: gray;">
		<span>Drop files here!</span>
	</div>
	</body>
</html>

Again, do not forget to change the PATH_TO_UPLOAD_HANDLER_SCRIPT.PHP.

I hope this article helps you.


Tags: , , , , , , , , , , ,

 
 
 
Content not available.
Please allow cookies by clicking Accept on the banner

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close