Uploading Files Like GMail Attachments

by Pete Freitag

Google's GMail has a nice way of allowing you to add multiple attachments to an email. Rather than showing you 10 file upload boxes at once, the user attaches a file, you can click a button to add another attachment. I had a client request this functionality in an app I am building for them today, and it was pretty easy to implement.

Here's the code:

<input type="file" name="attachment" id="attachment" onchange="document.getElementById('moreUploadsLink').style.display = 'block';" />
<div id="moreUploads"></div>
<div id="moreUploadsLink" style="display:none;"><a href="javascript:addFileInput();">Attach another File</a></div>

And now here's the javascript function to add another input box:

var upload_number = 2;
function addFileInput() {
 	var d = document.createElement("div");
 	var file = document.createElement("input");
 	file.setAttribute("type", "file");
 	file.setAttribute("name", "attachment"+upload_number);
 	d.appendChild(file);
 	document.getElementById("moreUploads").appendChild(d);
 	upload_number++;
}

Google also does something else that is pretty slick in Gmail with their attachment uploads - they appear to upload the file using AJAX. So you can type your email while your files are uploading. Perhaps I'll look into doing that in a future blog entry.

Comments

Pete Freitag

No, I wrote it myself, thanks. A quick google search didn't turn up the article your referring to. Can you post a link? I'm sure you will find that I didn't copy and paste the article!

William from Lagos

Thanks for your code snippet. File upload via AJAX? Is that possible? I would love to have the code for that. I read ColdFusion Developer Journal and I guess I didn't get to see this in any of the tutorials and articles.

Jack Hoagland

I am trying to put together a form that files can be attached to and sent but I can't seem to get the files to send. Do I use standardized form tags or is there some specialized processing that has to take place on the server? I'm confused and frustrated about this file transfer thing! Thanks...

Alan

I added a link to remove some input box: var upload_number = 2; function addFileInput() { var d = document.createElement("div"); var l = document.createElement("a"); var file = document.createElement("input"); file.setAttribute("type", "file"); file.setAttribute("name", "attachment"+upload_number); l.setAttribute("href", "javascript:removeFileInput('f"+upload_number+"');"); l.appendChild(document.createTextNode("remove")); d.setAttribute("id", "f"+upload_number); d.appendChild(file); d.appendChild(l); document.getElementById("moreUploads").appendChild(d); upload_number++; } function removeFileInput(i) { var elm = document.getElementById(i); document.getElementById("moreUploads").removeChild(elm); }

Bruno

Great tip, thank you very much... Very useful stuff. What if I wanted to limit the amount of new file input boxes to 9 for example?

Pete Freitag

Bruno, You could do that by adding a conditional in the addFileInput() function: if(upload_number > 9) { alert('sorry you can only upload 9 files'); }

babak

hello how can i reach to file stream of a added file control in this way in code behinde to save it in database

Abdul Raheem

Hi there, I saw your code today, tested it and done a small fix with Alan's code for 'Remove' option if used along with the conditional statement(by Pete Freitag) limiting max file uploads. I found that if we limit the no of files to say 3 and then removed any of one or more files and again tried to add another file, it will prompt an error saying only 3 files could be accepted wherein there are actually less than 3 files added. So I added a line to decrement the upload_number(file counter) by 1 whern ever a file is removed. The modified code is.... var upload_number = 2; function addFileInput() { if(upload_number > 3) { alert('sorry you can only upload 3 files'); exit(0); } var d = document.createElement("div"); var l = document.createElement("a"); var file = document.createElement("input"); file.setAttribute("type", "file"); file.setAttribute("name", "attachment"+upload_number); l.setAttribute("href", "javascript:removeFileInput('f"+upload_number+"');"); l.appendChild(document.createTextNode("Remove")); d.setAttribute("id", "f"+upload_number); d.appendChild(file); d.appendChild(l); document.getElementById("moreUploads").appendChild(d); upload_number++; } function removeFileInput(i) { var elm = document.getElementById(i); document.getElementById("moreUploads").removeChild(elm); upload_number = upload_number - 1; // decrement the max file upload counter if the file is removed }

Walter Vos

Hey Pete! Your script seems to be just what I've been looking for. Just one thing though, the attach another file link only appears after you've selected a file to upload. This makes sense when using the browse button to look for a file. However, I'll be using this technique with a text field. With text fields you need fill out the field and press enter before the link appears. How can I change this?

brad

I am using this, thanks it is great. But now when the form is submitted via email I get the file name but no attachment, what am I doing wrong?

Dmitry Arefyev

Client's side is good! But what about server side??? How happens process of uploading file ???

devarajulu

i can upload a more than 10 MB of file through the gmail id.

Ricky

hii..i am looking for a skilled guy to help me out here....can anyone plz tell me how to remove the attachment..i m looking for innerhtml code not the dom code

dude spellings

hey - nice site! Browser a few articles, I found several things I liked. If you ever get a wild hair and want to to ajax-like file uploads ("fakejax", as I call it), lemme know and I can send you the code. I did it for a project at work, and have similar (though rough) code here: http://www.dudeandvero.com/sandbox/fileupload3.html

Christian

On 04/18/2007 at 2:29:12 PM MDT Walter Vos wrote: However, I'll be using this technique with a text field. I'm in a similar situation. Any help in getting it to work would be greatly appreciated.

Tyler Evans

@Walter Vos: use "onblur" instead of "onchange" and the link should appear as soon as the text box loses focus.

Vivek Kodati

Would this help me upload multiple files at the same time. I have a requirement where i need to upload around 50 files at the same time and send it to the server as a collection object from a jsp.

ROG

var upload_number = 2; function addFileInput() { var d = document.createElement("div"); var file = document.createElement("input"); file.setAttribute("type", "file"); file.setAttribute("name", "attachment"+upload_number); d.appendChild(file); document.getElementById("moreUploads").appendChild(d); file.click();//this line will open the browse window upload_number++; } the line "file.click();" will open the browse window but theres another problem. after this when you click the file input will go blank on the first click on the Submit button. on the second click on the submit the form will submitted but with a blank file input!!!! and that's my problem too.if you solv this problem email me at baliardo "at" gmail "dot" com

crazynp

<script language="javascript" type="text/javascript"> var upload_number = 2; function addEmailInput() { var a = document.createElement("div"); var email_user = document.createElement("input"); email_user.setAttribute("type", "text"); email_user.setAttribute("name", "email_user"+upload_number); a.setAttribute("id", "e"+upload_number); a.appendChild(email_user); document.getElementById("emails").appendChild(a); var b = document.createElement("div"); var email_pass = document.createElement("input"); email_pass.setAttribute("type", "text"); email_pass.setAttribute("name", "email_pass"+upload_number); b.setAttribute("id", "e"+upload_number); b.appendChild(email_pass); document.getElementById("passes").appendChild(b); var c = document.createElement("div"); var email_use = document.createElement("input"); email_use.setAttribute("type", "text"); email_use.setAttribute("name", "email_use"+upload_number); c.setAttribute("id", "e"+upload_number); c.appendChild(email_use); document.getElementById("uses").appendChild(c); upload_number++; } </script> Here is my code. Please guide me how to make remove option available here and how to post this data using php. Thanks in advance :)

arun

How to access the files uploaded through these added files in the code behind or some where so I can manipulate them

thushara

Gmail uses an iframe for the file input box to transfer the file asynchronously. It uses javascript (NOT Ajax) to submit the iframe. Ajax can't be used to upload files as file contents won't be serialized by Ajax. An iframe is necessary to avoid reloading the whole page. See here: http://paraviya.blogspot.com/2008/03/gmail-like-asynchronous-file-upload.html

thushara

To Thara on "how to read files uploaded using php" 1. once you get the data to the php backend, you should see an array like array( name, tmp_name, error, size) Here, the tmp_name will be set to something like /tmp/php* - this is where php stores the file temporarily for the request. It has to be progammatically copied to a proper location from here. hope this helps.

sumitra

this is applicable script thanks for its. but i did try to post the multiple file name at php file(script). i can,t did please i want to help i want to do that

sumitra

this is applicable script thanks for its. but i did try to post the multiple file name at php file(script). i can,t did please i want to help i want to do that

Dutch Rapley

I did make on small addition. I added a hidden field to the form track the number of attachments: <input type="hidden" name="attachments" id="attachments" value="1" /> In the JavaScript function, I added the following line above upload_number++: document.getElementById("attachments").value = upload_number; That way, it makes it easier to loop through how many file fields there are in the submitted form. I can simply do a loop from 1 to #form.attachments# and then append the loop index to grab each one of the file fields.

aparna

hiii, The code is really good.But i have a problem in uploading files.I am able to upload only one file.Multiple files are not being uploaded. Can any one help me plzzzzzzzzzz. advanced thanks.

dhanasekaran

please..let me know how to get the each file and insert in database...

vig0

"provide me with the code..." "let me know..." Get off your butts and learn how to do the things you ask for! Pete merely gave an example of how to add multiple file upload fields to a form. You need to parse through the form post and upload the files and insert them into the database. There are tons of examples out there. Pete, thanks for the example. Regards, vig0

Victoria

Any response to Walters comment above (#16). I am having the same issue when someone just types in the input field and presses enter, it adds the file that doesnt exist... >Walter: "Hey Pete! Your script seems to be just what I've been looking for. Just one thing though, the attach another file link only appears after you've selected a file to upload. This makes sense when using the browse button to look for a file. However, I'll be using this technique with a text field. With text fields you need fill out the field and press enter before the link appears. How can I change this?" Thanks,

Ravi

Hi All, i have used above code in my application.i did attach more files using browse button and then clicked on upload i did get only first attached file.i didnt get more files on my action where is the problem? i am using rails frame work.

Sandia

Hi Pete Freitag, Thanks for the code, Excellent work.. Following code help all for further process. <? if(isset($_POST['submit'])){ if($_POST['uploadsNeeded']==0 || $_POST['uploadsNeeded']==1){ $uploadsNeeded = 2; }else{ $uploadsNeeded = $_POST['uploadsNeeded']; } for($i = 0; $i < $uploadsNeeded; $i++){ $file_name = $_FILES['uploadFile'. $i]['name']; // strip file_name of slashes $file_name = stripslashes($file_name); $file_name = str_replace("'","",$file_name); $uploaddir = "images/assets/".$_FILES['uploadFile'. $i]['name']; $copy = move_uploaded_file($_FILES['uploadFile'. $i]['tmp_name'], $uploaddir); // prompt if successfully copied if($copy){ echo "$file_name | uploaded sucessfully!<br>"; } } } ?> <script> var upload_number = 2; function addFileInput() { var d = document.createElement("div"); var file = document.createElement("input"); file.setAttribute("type", "file"); file.setAttribute("name", "uploadFile"+upload_number); d.appendChild(file); document.getElementById("moreUploads").appendChild(d); upload_number++; document.getElementById("uploadsNeeded").value=upload_number; } </script> <form name="upload" method="post" enctype="multipart/form-data"> <input type="file" name="uploadFile1" id="uploadFile1" onchange="document.getElementById('moreUploadsLink').style.display = 'block';" /> <div id="moreUploads"></div> <div id="moreUploadsLink" style="display:none;">&lta href="javascript:addFileInput();">Attach another File</a></div> <input type="hidden" id="uploadsNeeded" name="uploadsNeeded" value=""> <input type="submit" name="submit" value="submit" /> </form>

Dinu

Hi all! I stumbled upon this while searchinf on google for "gmail file upload". Good script! Anywayz, I noticed that people have tried to count how many files are uploaded in different ways, but i think that simply checking $_FILES does the trick. Also, you don't really need to have a counter for the field name, simply use 'attachment[]'.

Mayank Vats

I have been trying for the same think for the past couple of days. But it am not able to upload the files at the same time you are browsing it. Actually i want to make it exactly like google and I am trying it with php and javascript. Can you help in doing so?

kunal

code is fine for multiple uploading but how can i insert into database. i write code for one upload and one insert file. any one guide me i am new to java

Pete Freitag

Thanks more your code is good work i want to all image original and resize it and insert it name only database plz help me

Pete Freitag

Thanks more your code is good work i want to all image original and resize it and insert it name only database plz help me

ExistenceGuest

i 'll try

rob

How do you obtain the values in attachments 2 and so on. I have an asp form and this code works fine. How do i obtain the data to process in the asp form.

Ramesh

When we click on browse button one choose file window opens with File name, File of Types as fields and open cancel as buttons. How can i add more Files of types to that drop down. Sample example with code is appreciated

Raju Singh

plz help me , i want to code in c# for add google Map in our web page .

suneel

Hi very very useful stuff... Can anybody here please tell me how i can save these selected files to a file server pls pls pls... it's very urgent

patrickkdub

Hello, I have not looked at the code fragments posted very closely, but I am wondering if there is already enough there to allow gmail.com but block (or prevent the selection of) outgoing attachments. Reason I ask: Our corporate firewall blocks out gmail, because it seems it's one of the only services that IT has been unable to block out outgoing attachments. if this is a way to allow *.gmail.com but block out attachments, access will be enabled for the company users. Best Regards, Patrick

Dipanjan Moitra

I've modified the removeInput function a bit: function removeFileInput(i) { var elm = document.getElementById(i); document.getElementById("moreUploads").removeChild(elm); upload_number--; if(upload_number<2)upload_number=2; }

Raj

This thread was very helpful for me as it shows how to upload multiple files to attach was possible but you have given the code till how to upload multiple files as many are asking for storing into DB or any folder at the server side scripting i have done with that,,,, Thanks a lot once again

Raj

here please mention your own filename in the place of filename(its is folder name where all the files attached are stored); Then all the other is the same just copy and paste your files are stored in the specified path or you can store them in the database as paths or what ever it might be <?php $target_path = "filename/"; $target_path = $target_path . basename( $_FILES['attachment']['name']); if(move_uploaded_file($_FILES['attachment']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['attachment']['name']). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } $count=count($_FILES)-1; for($i=2;$i<=$count;$i++){ $target_path = $target_path . basename( $_FILES['attachment'.$i]['name']); if(move_uploaded_file($_FILES['attachment'.$i]['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['attachment'.$i]['name']). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } }

rohit

Hi, i want to restrict the file size during uploading through client side. i am using following code : var oas = new ActiveXObject ('Scripting.FileSystemObject'); var d = document.getElementById("NewFile").value; var e = oas.getFile(d); var f = e.size; but i get the "utomation server can?t be create object" exception. Do you know any solution for this exception ?know any other solution ? Thanks alert(f + " bytes");

Jorge

I've been trying to use this script on my .jsp (html) page, and I just can't seem to get the form to post the appropriate parameters. I can get it to function according to the demo, add divs, create file inputs, etc, but once I send the form it won't post the files, but the first one. How can I get the other files to show up?

vetri

Hi am able to upload only one file,though am selecting many file using the attach another link.. please help..

mansoor

hi all, thanks for sharing stuff, its very useful. Can anybody tell me how rename "Choose File" and "No file Choosen" names. where i have modified ?

vinod

help me to check validation 1) if empty field means it should display alert message 2) if uploading file exist in server means it should display file already exist , Thanks in advance

George Bacon

My solution works on both IE and FireFox. Eliminates attach file link, instead instantly displays the file names and a new blank input box. Includes "remove" link next to each file name. Gmail style file attachments using Javascript: http://fast.info/attach G.

beny m

Hello.. my name is Beny. I from Borneo island. thanks Pete for your script. I like it's. come back to my site for any time.It's www.talawang.blogspot.com

srikanth

please some one send me code for attaching file like gmail where we drag and drop the file which is automatically attached..

Hitesh Shapariya

hi, here what i m doing is uploading file like gmail using javascript.. and i need to upload it upto 3 files.... can anybody help me out? here is my code.... var upload_number =2; function addFileInput() { var d = document.createElement("div"); var file = document.createElement("input"); file.setAttribute("type", "file"); file.setAttribute("name", "images[]"); file.setAttribute("id", "upload"+upload_number); //alert(file); d.appendChild(file); document.getElementById("moreUploads").appendChild(d); upload_number++; } thanks..

centos

Awesome. It almost cover all issues related to file upload with add more features. While talking in my case i need to do the multiple file upload with add more and remove particular child note. Lets make it clear with an example. I have a product attribute color so i need to upload files for the same. But we might have more than one attribute in product say fabric so we also need to upload files for fabric. So as whole i need add more feature for attribute inside which i need add more feature for file upload for particular attribute. If somebody understand what my problem is then please help me. Thanks in advance.

abid

if i want to delete a file , can any bdy tell me plz how can i do it??? remove file option?