Pete Freitag Pete Freitag

Uploading Files Like GMail Attachments

Published on October 06, 2006
By Pete Freitag
web

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.



javascript html dhtml google gmail upload forms attachments

Uploading Files Like GMail Attachments was first published on October 06, 2006.

If you like reading about javascript, html, dhtml, google, gmail, upload, forms, or attachments then you might also like:

Discuss / Follow me on Twitter ↯

Comments

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!
by Pete Freitag on 10/06/2006 at 9:54:16 AM UTC
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.
by William from Lagos on 10/06/2006 at 12:17:38 PM UTC
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...
by Jack Hoagland on 10/11/2006 at 2:34:34 PM UTC
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);
}
by Alan on 11/07/2006 at 5:59:24 AM UTC
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?
by Bruno on 11/20/2006 at 12:56:38 PM UTC
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'); }
by Pete Freitag on 11/20/2006 at 1:40:59 PM UTC
hello
how can i reach to file stream of a added file control in this way in code behinde to save it in database
by babak on 02/06/2007 at 1:46:38 AM UTC
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
}
by Abdul Raheem on 04/02/2007 at 1:59:40 AM UTC
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?
by Walter Vos on 04/18/2007 at 2:29:12 PM UTC
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?
by brad on 05/09/2007 at 12:19:53 PM UTC
Client's side is good! But what about server side???
How happens process of uploading file ???
by Dmitry Arefyev on 06/01/2007 at 7:51:07 AM UTC
i can upload a more than 10 MB of file through the gmail id.
by devarajulu on 07/13/2007 at 2:30:48 AM UTC
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
by Ricky on 08/14/2007 at 4:26:36 AM UTC
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
by dude spellings on 10/12/2007 at 2:34:08 PM UTC
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.
by Christian on 10/16/2007 at 10:38:54 AM UTC
@Walter Vos:
use "onblur" instead of "onchange" and the link should appear as soon as the text box loses focus.
by Tyler Evans on 10/17/2007 at 9:32:09 PM UTC
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.
by Vivek Kodati on 12/11/2007 at 1:07:13 AM UTC
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
by ROG on 01/01/2008 at 2:30:22 AM UTC
<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
:)
by crazynp on 01/25/2008 at 1:15:52 PM UTC
How to access the files uploaded through these added files in the code behind or some where so I can manipulate them
by arun on 02/20/2008 at 5:12:26 AM UTC
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
by thushara on 03/10/2008 at 5:29:16 PM UTC
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.
by thushara on 03/10/2008 at 5:39:56 PM UTC
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
by sumitra on 03/19/2008 at 12:33:05 AM UTC
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
by sumitra on 03/19/2008 at 12:33:06 AM UTC
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.
by Dutch Rapley on 03/25/2008 at 11:18:23 AM UTC
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.
by aparna on 04/03/2008 at 6:30:34 AM UTC
please..let me know how to get the each file and insert in database...
by dhanasekaran on 05/09/2008 at 7:48:58 AM UTC
"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
by vig0 on 05/19/2008 at 12:28:51 PM UTC
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,
by Victoria on 06/02/2008 at 9:38:43 AM UTC
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.
by Ravi on 06/05/2008 at 5:02:39 AM UTC
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>
by Sandia on 06/17/2008 at 6:04:52 AM UTC
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[]'.
by Dinu on 07/22/2008 at 1:43:31 PM UTC
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?
by Mayank Vats on 07/30/2008 at 6:55:02 AM UTC
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
by kunal on 11/19/2008 at 5:15:53 AM UTC
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
by Pete Freitag on 01/14/2009 at 6:51:20 AM UTC
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
by Pete Freitag on 01/14/2009 at 7:04:23 AM UTC
i 'll try
by ExistenceGuest on 01/24/2009 at 11:30:32 PM UTC
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.
by rob on 03/18/2009 at 10:13:37 PM UTC
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
by Ramesh on 09/07/2009 at 11:37:30 PM UTC
plz help me ,

i want to code in c# for add google Map in our web page .
by Raju Singh on 10/01/2009 at 3:43:23 PM UTC
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
by suneel on 11/05/2009 at 9:55:20 AM UTC
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
by patrickkdub on 01/19/2010 at 7:17:30 AM UTC
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;
}
by Dipanjan Moitra on 01/22/2010 at 7:06:05 AM UTC
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
by Raj on 04/19/2010 at 4:48:47 AM UTC
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!";
}
}
by Raj on 04/19/2010 at 4:54:54 AM UTC
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");
by rohit on 06/16/2010 at 2:40:40 PM UTC
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?
by Jorge on 07/30/2010 at 4:10:34 PM UTC
Hi am able to upload only one file,though am selecting many file using the attach another link..

please help..
by vetri on 08/02/2010 at 5:39:05 AM UTC
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 ?
by mansoor on 03/01/2011 at 2:50:43 PM UTC
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
by vinod on 03/10/2011 at 12:16:05 AM UTC
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.
by George Bacon on 04/19/2011 at 2:19:22 AM UTC
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
by beny m on 05/01/2011 at 9:52:44 PM UTC
please some one send me code for attaching file like gmail where we drag and drop the file which is automatically attached..
by srikanth on 06/13/2011 at 4:44:23 AM UTC
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..
by Hitesh Shapariya on 06/29/2011 at 2:31:39 AM UTC
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.
by centos on 07/07/2011 at 10:36:17 PM UTC
if i want to delete a file , can any bdy tell me plz how can i do it???

remove file option?
by abid on 07/29/2012 at 4:42:03 AM UTC