Friday, September 20, 2024

Uploading Files Like GMail Attachments

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

Related Entries

  • Cheat Sheet Roundup – Over 30 Cheatsheets for developers – September 1, 2005
  • Tracking JavaScript Events with Google Analytics – September 28, 2006
  • Howto Build a Form That Isn’t Annoying (Part 2) – May 3, 2006
  • Styling Your forms with CSS and Labels – January 11, 2006
  • Blocking Mozilla / Google Prefetch – April 6, 2005
  • * View Original Post

    Pete Freitag (http://www.petefreitag.com/) is a software engineer, and
    web developer located in central new york. Pete specializes in the
    HTTP protocol, web services, xml, java, and coldfusion. In 2003 Pete
    published the ColdFusion MX Developers Cookbook with SAMs Publishing.

    Pete owns a Firm called Foundeo (http://foundeo.com/) that specializes
    in Web Consulting, and Products for Web Developers.

    Related Articles

    1 COMMENT

    LEAVE A REPLY

    Please enter your comment!
    Please enter your name here

    Latest Articles