Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    New to the CF scene
    Join Date
    Mar 2012
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Have Upload Script, Need It Edited For Multi-Uploads on one page

    Hello All,
    I found this awesome upload script and it works perfectly for what I need so far. The one problem is I can't get it to work for multiple (individual files).
    The script works like a user will click the browse button, select the file, and it auto submits uploading the file. Now the script is setup to handle multiple files selected all at once, but I need separate buttons for each file.

    So here is the main page
    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>HTML5 File API</title>
        <link rel="stylesheet" href="style.css" />
    </head>
    <body>
    	<div id="main">
    		<h1>Upload Your Images</h1>
    		<form method="post" enctype="multipart/form-data"  action="upload.php">
        		<input type="file" name="images" id="images"/>
        		<input type="file" name="images" id="images"/>
        		<input type="file" name="images" id="images"/>
        		<button type="submit" id="btn">Upload Files!</button>
        	</form>
    
      	<div id="response"></div>
    		<ul id="image-list">
    
    		</ul>
    	</div>
    	
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
      <script src="upload.js"></script>
    </body>
    </html>
    Here is the upload.php file
    Code:
    <?php
    
    foreach ($_FILES["images"]["error"] as $key => $error) {
        if ($error == UPLOAD_ERR_OK) {
            $name = $_FILES["images"]["name"][$key];
            move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
        }
    }
    
    
    echo $_FILES['images']['name'][$key];
    ?>
    And the upload.js file
    Code:
    (function () {
    	var input = document.getElementById("images"), 
    		formdata = false;
    
    
    	if (window.FormData) {
      		formdata = new FormData();
      		document.getElementById("btn").style.display = "none";
    	}
    	
     	input.addEventListener("change", function (evt) {
     		document.getElementById("response").innerHTML = "Uploading . . ."
     		var i = 0, len = this.files.length, img, reader, file;
    	
    		for ( ; i < len; i++ ) {
    			file = this.files[i];
    	
    				if ( window.FileReader ) {
    					reader = new FileReader();
    					reader.onloadend = function (e) { 
    						showUploadedItem(e.target.result, file.fileName);
    					};
    					reader.readAsDataURL(file);
    				}
    				if (formdata) {
    					formdata.append("images[]", file);
    				}
    		}
    	
    		if (formdata) {
    			$.ajax({
    				url: "upload.php",
    				type: "POST",
    				data: formdata,
    				processData: false,
    				contentType: false,
    				success: function (res) {
    					document.getElementById("response").innerHTML = res; 
    				}
    			});
    		}
    	}, false);
    }());
    I'm good with php, but don't know much with javascript and jquery so I don't really know how this works. Is there a way to adjust this so the multiple file inputs will upload. Right now it will only upload the first one.

    Here is it working. http://www.skafreaks.com/new2/upload/

    Thanks for any help
    SkaFreaks

  • #2
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,461
    Thanks
    11
    Thanked 600 Times in 580 Posts
    replace
    Code:
        		<input type="file" name="images" id="images"/>
        		<input type="file" name="images" id="images"/>
        		<input type="file" name="images" id="images"/>
    with
    Code:
        		<input type="file" name="images" id="images" multiple />
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%

  • #3
    New to the CF scene
    Join Date
    Mar 2012
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thanks for the reply!
    Unfortunately that isn't what I was hoping for. As stated above I need seperate buttons for each file (meaning one file one button).
    Basically the total page is a larger form with a track listings for a cd. The user will be able to edit the track info (name, length, etc.) as well as upload an mp3 for each track. Once it is uploaded I plan to have the end result put the filename in an input field and then when the user submits the form it will put the name of the mp3 into the database along side all the other data.

    Hopefully this makes things clearer on what I am trying to accomplish and there might be a way to do this.

    Thanks
    SkaFreaks

  • #4
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,461
    Thanks
    11
    Thanked 600 Times in 580 Posts
    Quote Originally Posted by SkaFreaks View Post
    Thanks for the reply!
    Unfortunately that isn't what I was hoping for. As stated above I need seperate buttons for each file (meaning one file one button).
    Basically the total page is a larger form with a track listings for a cd. The user will be able to edit the track info (name, length, etc.) as well as upload an mp3 for each track. Once it is uploaded I plan to have the end result put the filename in an input field and then when the user submits the form it will put the name of the mp3 into the database along side all the other data.

    Hopefully this makes things clearer on what I am trying to accomplish and there might be a way to do this.

    Thanks
    SkaFreaks
    it's much better ui to allow more than one file. a file chooser is about as bad as a pop-up. it is a popup, and it should be minimized.

    i'm not sure why you would need extra clutter on a form. the jQuery code you posted is expecting the multiple attrib already...

    i would think selecting a dozen files and clicking ok would be a lot faster than 12 clicks. sometimes the browse box starts out in some dumb place like the desktop each time it's opened. At any rate, once the files are selected and "ok" is clicked, you would loop through the FileList and append a section on your form for each file to gather notes, title, length, etc. You can pre-fill the form with file-name, file-date, and file-size information from each File object.

    if these are MP3s, you can even extract the ID3 info from the file to assist you and the client in gathering meta, or use an web-service to search the file-name and fetch flickr or yahoo images from the resulting keywords. Playlist files often contain track length; it may be worth it to load and parse them, again to pre-fill the form as a convenience to the up-loader. if they are uploading images, you can show them and validate dimension restrictions before uploading.

    once the meta info is correct (use html5 form validation to make sure it is), click 'submit' and away they go to php land.
    Last edited by rnd me; 03-26-2012 at 04:43 PM.
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%

  • Users who have thanked rnd me for this post:

    SkaFreaks (03-26-2012)

  • #5
    New to the CF scene
    Join Date
    Mar 2012
    Posts
    3
    Thanks
    1
    Thanked 0 Times in 0 Posts
    I guess that would make more sense. For myself it would be easier to do it the way I was suggesting just cause now it's getting in to stuff I haven't yet learned how to do. While I feel I know quite a bit I am still just an amateur Web Designer and do it for the fun of it. I guess I need to start learning some new stuff now.

    Thanks for the replies!
    SkaFreaks

  • #6
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,461
    Thanks
    11
    Thanked 600 Times in 580 Posts
    here is an example hybrid that uses normal file uploads, coupled with potentially extra meta from forms.
    it doesn't use jQuery or ajax, but provides the kind of interaction i was talking abobut.
    feel free to modify, adding extra form fields as needed or renaming stuff. i didn't match it exactly to your php, but you're probably better at that than i...

    at any rate, this is along the lines of i was talking about. i don't think it's that's complicated, but i can see how it might be a bit much up-front.


    Code:
    <html>   
    <head>
     <title> Load Many Files</title>
     <style>
       i { display: inline-block; width: 6em; padding-right: 1em;	text-align: right;}
       li input { width: 24em; border:1px solid #888; background:rgba(255,255,255,0.5);}
       li { margin: 0.5em 0.2em; background:#ddd;inline-block; width: 44em; box-shadow: 1px 1px 3px rgba(0,0,0,0.4); padding: 3px; overflow:hidden;}
     </style>
    </head>
    <body>
      <form action="/upload.php" method="POST" enctype="multipart/form-data">
    	<input name="files" type="file" multiple onchange="grabFiles(this);return true;" />
    	<div id="results"></div>
    	<input type="submit" value="Upload These Files"/>
      </form>
    <script>
    
    function el(tid) {return document.getElementById(tid);}
    
    function template(ob, str){ //turns a string and an object into a new string
       return str.replace(/\{{2}([^}]+?)\}{2}/g, 
         function(j,a){  return ob[a]||"";  } );
    }//end template()
    
    
    function complete(files){ //when all file's meta has been harvested, display the array of objects as an html list:
       el("results").innerHTML="<ol>"+
       files.map(function(file, index){
          return template(file, 
    	"<li>	\
     	  <time date-time='{{date}}'>{{date}}</time> \
    	  <i>{{size}}</i>	\
    	  <i>{{type}}</i>	\
    	  <b><input value='{{title}}' name='filename_"+index+"'/></b>	\
    	</li>"	
          );
        }).join("\n")+"</ol>";
    }//end complete()
    
    
    
    function grabFiles(elm){ //loads file meta into an array of objects:
    	var files=[].slice.call(elm.files),
    	  stack=[],
    	  count=files.length;
    	el("results").innerHTML="Loading Files ("+count+" left)";
    	files.forEach(function(file, i){
    	 var reader=new FileReader();
    	 reader.onload= function(event){  
    	    stack[stack.length]={
    		date: 	file.lastModifiedDate,
    		type: 	file.type,
    		title: 	file.name,
    		size: 	Math.floor(event.target.result.length / 1024)+"kb"
    	    };	
    
    	    if(!--count){ complete(stack); }else{el("results").innerHTML="Loading Files ("+count+" left)";}
    
    	  };//end reader.onload()
    
    	  reader.readAsBinaryString(file);
    	})//end forEach()
    
    }//end grabFiles()
    
    
    </script>
    </body>
    </html>
    Last edited by rnd me; 03-27-2012 at 06:31 AM.
    my site (updated 2014/10/20)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.3, IE11:9.2, IE9:2.7, IE10:2.6, FF:16.8, CH:47.5, SF:7.8, NON-MOUSE:37%

  • #7
    Banned
    Join Date
    Mar 2012
    Posts
    306
    Thanks
    1
    Thanked 28 Times in 28 Posts
    Quote Originally Posted by SkaFreaks View Post
    As stated above I need seperate buttons for each file (meaning one file one button).
    Code:
            <form method="post" enctype="multipart/form-data"  action="upload.php">
                <fieldset id="uploadPrompts">
                    <input type="file" name="images[]" />
                </fieldset>
                <button type="button" onclick="addFilePrompt();">Add Upload File</button>
                <input type="submit"  value="Upload Files!"/>
            </form>
            <script>
                var fldSet = document.getElementById('uploadPrompts');
                function addFilePrompt(){
                    fldSet.appendChild(document.createElement('br'));
                    fldSet.appendChild(document.getElementsByName('images[]')[0].cloneNode(true));
                }
            </script>
    Last edited by Mishu; 03-27-2012 at 07:55 AM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •