logo



Code examples - MyUploader
Example 1:
Sends an email notification after the upload.
Download: PHP, Java, Struts 1, ASP.NET, C#, Classic ASP

Example 2:
Shows a list of the upload files on the success page. This example uses sessions.
Download: PHP, Java, ASP.NET, C#, Classic ASP

Example 3:
MyUploader with form based authentication. This example uses sessions.
Download: PHP

The examples are based on the following code.
Base code examples

yes Servlet
yes JSP
yes ASP.NET
yes C#
yes Classic ASP
yes PHP
yes Perl
yes Coldfusion

The following Java Servlet uses the libraries Commons FileUpload 1.1.1 and Commons IO 1.2 of Apache. To download the required libraries, click here for Apache FileUpload and here for Apache IO. The Servlet runs in an application server, such as the Open Source application server Apache Tomcat. See the documentation of your application server for installing the Servlet.

The Servlet stores the files in the directory '/tmp' - you can change this if you like, to for example 'c://temp' for a Windows environment. To download the Servlet click here.

package uploadserver;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Class for storing the uploaded files.
 * 
 * @author JavaAtWork
 */
public class UploadServlet extends HttpServlet {

  /**
    * The base upload directory. In this directory all uploaded files will
    * be stored. With the applet param tag 'directory' you can create a
    * subdirectory for a user. 
    * See http://www.javaatwork.com/parameters.html#directory for more 
    * information about the 'directory' param tag. For a Windows environment 
    * the BASE_DIRECTORY can be e.g. * 'c:/temp' for Linux environment '/tmp'.
    */
  private static final String BASE_DIRECTORY = "/tmp";

  protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    // check if the http request is a multipart request
    // with other words check that the http request can have uploaded files
    if (isMultipart) {

      //  Create a factory for disk-based file items
      FileItemFactory factory = new DiskFileItemFactory();

      //  Create a new file upload handler
      ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

      // Set upload parameters
      // See Apache Commons FileUpload for more information
      // http://jakarta.apache.org/commons/fileupload/using.html
      servletFileUpload.setSizeMax(-1);

      try {

        String directory = "";

        // Parse the request
        List items = servletFileUpload.parseRequest(request);

        // Process the uploaded items
        Iterator iter = items.iterator();

        while (iter.hasNext()) {
          FileItem item = (FileItem) iter.next();

          // the param tag directory is sent as a request parameter to
          // the server
          // check if the upload directory is available
          if (item.isFormField()) {

            String name = item.getFieldName();

            if (name.equalsIgnoreCase("directory")) {

              directory = item.getString();
            }

            // retrieve the files
          } else {

            // the fileNames are urlencoded
            String fileName = URLDecoder.decode(item.getName());

            File file = new File(directory, fileName);
            file = new File(BASE_DIRECTORY, file.getPath());

            // retrieve the parent file for creating the directories
            File parentFile = file.getParentFile();

            if (parentFile != null) {
              parentFile.mkdirs();
            }

            // writes the file to the filesystem
            item.write(file);
          }
        }

      } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      }

      response.setStatus(HttpServletResponse.SC_OK);

    } else {
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }
  }
}




The following JSP uses the libraries Commons FileUpload 1.1.1 and Commons IO 1.2 of Apache. To download the required libraries, click here for Apache FileUpload and here for Apache IO. The JSP runs in an application server, such as the Open Source application server Apache Tomcat. See the documentation of your application server for installing the JSP.

The JSP stores the files in the directory '/tmp' - you can change this if you like, to for example 'c://temp' for a Windows environment. To download the JSP click here.

<%@ page import="java.io.*" %>
<%@ page import="java.net.*" %>
<%@ page import="java.util.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>

<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

// check if the http request is a multipart request
// with other words check that the http request can have uploaded files
if (isMultipart) {

  
  // The base upload directory. In this directory all uploaded files will
  // be stored. With the applet param tag 'directory' you can create a
  // subdirectory for a user. 
  // See http://www.javaatwork.com/parameters.html#directory for more 
  // information about the 'directory' param tag. For a Windows environment 
  // the base_directory can be e.g. 'c:/temp' for Linux environment '/tmp'.
  String base_directory = "c:/temp";

  // Create a factory for disk-based file items
  FileItemFactory factory = new DiskFileItemFactory();

  // Create a new file upload handler
  ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

  // Set upload parameters
  // See Apache Commons FileUpload for more information
  // http://jakarta.apache.org/commons/fileupload/using.html
  servletFileUpload.setSizeMax(-1);

  try {

    String directory = "";

    // Parse the request
    List items = servletFileUpload.parseRequest(request);

    // Process the uploaded items
    Iterator iter = items.iterator();

    while (iter.hasNext()) {
      FileItem item = (FileItem) iter.next();

      // the param tag directory is sent as a request parameter to the server
      // check if the upload directory is available
      if (item.isFormField()) {

        String name = item.getFieldName();

        if (name.equalsIgnoreCase("directory")) {

          directory = item.getString();
        }

        // retrieve the files
      } else {

        // the fileNames are urlencoded
        String fileName = URLDecoder.decode(item.getName());

        File file = new File(directory, fileName);
        file = new File(base_directory, file.getPath());

        // retrieve the parent file for creating the directories
        File parentFile = file.getParentFile();

        if (parentFile != null) {
          parentFile.mkdirs();
        }

        // writes the file to the filesystem
        item.write(file);
      }
    }

  } catch (Exception e) {
    e.printStackTrace();
    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
  }
}

%>



The ASP.NET example stores the files in the directory 'c:\temp\'. The directory can be changed with the variable 'baseDirectory', see below. To download the ASP.NET code click here.

By default, ASP.NET only allows files up to 4096KBytes (4MB) in size to be uploaded to the web server. To upload larger files, you will need to change the maxRequestLength and executionTimeout parameter of the <httpRuntime> section found in the web.config and/or machine.config file.

<%@ import namespace="System.IO" %>

<script language="vb" runat="server">

Protected Sub Page_Load(s As Object, e As EventArgs)

   Try
      Dim baseDirectory As String = "c:\temp\"           
      Dim uploadDirectory As String = Request("directory")
      Dim combination1 As String
      Dim PostedFile As HttpPostedFile

      If Not uploadDirectory  = "" Then
         combination1 = Path.Combine(baseDirectory , uploadDirectory)
      Else
         combination1 = baseDirectory
      End If

      For i As Integer = 0 To Request.Files.Count - 1

         PostedFile = Request.Files(i)

         ' Creates the full path
         Dim combination2 As String = _
         Path.Combine(combination1, HttpUtility.UrlDecode(PostedFile.FileName))   

         ' Create the directories
         Dim dir As New DirectoryInfo(Path.GetDirectoryName(combination2))
         dir.Create                          

         ' Save the uploaded file
         PostedFile.SaveAs(combination2)

      Next

   Catch ex As Exception

      Console.WriteLine("Exception occurred: ", ex.ToString())

      ' Internal server error
      Response.StatusCode = 500               

   End Try

End Sub

</script>



The C# example stores the files in the directory 'c:\temp\'. The directory can be changed with the variable 'baseDirectory', see below. To download the C# code click here.

By default, C# only allows files up to 4096KBytes (4MB) in size to be uploaded to the web server. To upload larger files, you will need to change the maxRequestLength and executionTimeout parameter of the <httpRuntime> section found in the web.config and/or machine.config file.

<%@ Page Language="C#" %>
<%@ Import namespace="System.IO" %>

<script language="C#" runat="server">

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
       String baseDirectory = "c:\\temp";
       String uploadDirectory = Request["directory"];
       String folders;
       HttpPostedFile PostedFile;

       if (uploadDirectory != null && uploadDirectory != "")
       {
           folders = Path.Combine(baseDirectory, uploadDirectory);
       }
       else
       {
           folders = baseDirectory;
       }

       for (int i = 0; i < Request.Files.Count; i++)
       {
           PostedFile = Request.Files[i];

           // Creates the full path
           String filePath = Path.Combine(folders, HttpUtility.UrlDecode(PostedFile.FileName));

           // Create the directories
           DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(filePath));
           dir.Create();

           // Save the uploaded file
           PostedFile.SaveAs(filePath);
        }
    }
    catch(Exception ex)
    {
        // Internal server error
        Response.StatusCode = 500;
        Response.Status = "500 Error: " + ex.ToString();
    }
}
</script>



To download the sample code click here. The files will be stored in the folder "c:\temp\". To change this update the base_directory and change if necessary the permissions of the directory.

For IIS6.0 users the maximum upload size is limited to the value of the AspMaxRequestEntityAllowed property. The default size is 200,000 Bytes (200 KB). To change the value open the metabase.XML file which is located in c:\Windows\System32\Inetsrv and change the value of AspMaxRequestEntityAllowed to e.g. 104857600, this is 100mb. You need to stop the IIS Service before you can edit the file.

See for more information: http://support.microsoft.com/kb/327659.


Place the following php code in a file with extension php (e.g. upload.php), then change the base_directory. The base_directory is the root directory where the uploaded files will be stored. In the next example, the base_directory is "c:/temp" - you can change this if you like to e.g. "/tmp/images" for a Linux environment. The base_directory must already exist.

PHP can retrieve as default files up to 2MB. If you need to upload larger files you must change the following settings of the php.ini file (for example):

upload_max_filesize = 50M ; Maximum allowed size for uploaded files (max: 1990M).
post_max_size = 60M ; Maximum size of POST data that PHP will accept (max: 1990M).
memory_limit = 70M ; Maximum amount of memory a script may consume (max: 1990M).
max_file_uploads = 100 ; Since PHP version 5.2.12

Large files requires also more resources. You need probably also change the following settings:

max_execution_time = 30 ; Maximum execution time of each script, in seconds
max_input_time = 60 ; Maximum amount of time each script may spend parsing request data

See for more information: php.

<?php

$base_directory = "uploaded-files";
$directory = $_REQUEST['directory'];
$upload_dir = "";
$file = "";
$dir = "";

$POST_MAX_SIZE = ini_get('post_max_size');
$mul = substr($POST_MAX_SIZE, -1);
$mul = ($mul == 'M' ? 1048576 : ($mul == 'K' ? 1024 : ($mul == 'G' ? 1073741824 : 1)));

// check if the size is not larger than the size of the php.ini file
if ($_SERVER['CONTENT_LENGTH'] > $mul*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
	
   error_log("Total upload size is larger than post_max_size directive in the " . 
      "php.ini file ($POST_MAX_SIZE)");
   error_log("The php.ini file is the configuration file of PHP");
   error_log("Please check and change the post_max_size, upload_max_filesize " . 
      "and memory_limit directives");
   error_log("The maximum value of these directives is 1990M");
   error_log("Increase also the max_execution_time and the max_input_time directives");
   header("HTTP/1.0 500 Internal Server Error");
   exit;
}

// check if $base_directory exist
if (!is_dir($base_directory)) {
     
     error_log('The $base_directory \'' . $base_directory . "' does not exist");
     error_log('Please check the $base_directory in the upload.php script');
     header("HTTP/1.0 500 Internal Server Error");
     exit;
}

// check if the $base_directory is writeable
if (!is_writeable($base_directory)) {
     error_log("The base_directory '" . $base_directory . "' has no write permissions.");
     header("HTTP/1.0 500 Internal Server Error");
     exit;
}

determineUploadDirectory();

foreach ($_FILES["userfile"]["error"] as $key => $error) {

   if ($error == UPLOAD_ERR_OK) {

      $tmp_name = $_FILES["userfile"]["tmp_name"][$key];

      $name = $_FILES["userfile"]["name"][$key];

      $decoded_name = urldecode($name);

      $pos = strrpos($decoded_name, "/");

      if ($pos === false) { 
         $file = $decoded_name;
         $path = $upload_dir;
      } else {
         $file = substr($decoded_name, $pos + 1);
         $dir = substr($decoded_name, 0, $pos);
         $path = $upload_dir . "/" . $dir;
      }	
      
      mkdir_recursive($path);
      
      if(!move_uploaded_file($tmp_name, $path . "/" . $file)) {
         if (!is_dir($path)) {
	    error_log("File: '" . $file . "' cannot be saved because the directory '" 
              . $path . "' does not exist.");
         } else if (!is_writeable($path)) {
            error_log("File: '" . $file . "' cannot be saved because the directory '" 
             . $path . "' has no write permissions.");
	 }
      }

   } else {
      switch ($error) {
         case UPLOAD_ERR_INI_SIZE:
            error_log("The uploaded file exceeds the upload_max_filesize directive (" 
             . ini_get("upload_max_filesize") . ") in php.ini.");
            break;
         case UPLOAD_ERR_FORM_SIZE:
            error_log("The uploaded file exceeds the MAX_FILE_SIZE directive that" 
             . " was specified in the HTML form.");
            break;
         case UPLOAD_ERR_PARTIAL:
            error_log("The uploaded file was only partially uploaded.");
            break;
         case UPLOAD_ERR_NO_FILE:
            error_log("No file was uploaded.");
            break;
         case UPLOAD_ERR_NO_TMP_DIR:
            error_log("Missing a temporary folder.");
            break;
         case UPLOAD_ERR_CANT_WRITE:
            error_log("Failed to write file to disk");
            break;
      }   
   
      header("HTTP/1.0 500 Internal Server Error");
      exit;
   }
}

//-----------------------------------------------------------------------------
//  FUNCTIONS
//-----------------------------------------------------------------------------

// Creates the uploaddirectory. The uploaddirectory is based on the
// base_directory and the directory. The directory is the unique
// directory for every user. You can specify this directory in the
// param tag of the applet tag. See http://www.javaatwork.com/parameters.html
// The base_directory is specified in this php script.
// This method ensures that there's only one slash between the directories.
// e.g. c:/temp/files instead of c:/temp//files
function determineUploadDirectory() {

   global $base_directory, $directory, $upload_dir;

   //remove the slash of base_directory
   $len = strlen ($base_directory);

   $charAt = $base_directory{$len -1};

   if ($charAt == '/') {
      $base_directory =  substr ($base_directory, 0, $len -1);
   }

   // remove the slashes from $directory
   $charAt = $directory{0};

   if ($charAt == '/') {
      $directory =  substr($directory, 1);
   }

   $len = strlen ($directory);

   if ($len != 0) {
      $charAt = $directory{$len - 1};

      if ($charAt == '/') {
         $directory =  substr($directory, 0, $len -1);
      }

      $len = strlen ($directory );

      $upload_dir = $base_directory . "/" . $directory;
   } else {
      $upload_dir = $base_directory;
   }
}

// Creates the directories if needed.
function mkdir_recursive($dir){

   do {
      $tempdir = $dir;
      while (!is_dir($tempdir)) {
         $basedir = dirname($tempdir);

         if ($basedir == '/' || is_dir($basedir)) {
            mkdir($tempdir,0757);

            // sometimes the chmod in the mkdir method doesn't work
            chmod($tempdir, 0757);

         } else {
            $tempdir=$basedir;
         }
      }
   } while ($tempdir != $dir);
}
?>

The Perl example stores the files in the directory '/tmp/files' - you can change this for your own needs to for example 'c:/temp/files' for a Windows environment.

The first line of the code below is the location of the perl interpreter. On a Linux machine this is often #!/usr/local/bin/perl or #!/usr/bin/perl. If you executed the script and you will get an 500 http response code than probably the location is incorrect.

The Perl example uses the CGI.pm library. Be sure that the script has 755 file permissions. You can change the permissions with most FTP Clients.
#!/usr/local/bin/perl

$base_directory = "/tmp/files";
$max_file_size = 100*1024*1024; # 100 MB, -1: unlimited

use CGI qw/:standard/;

$CGI::POST_MAX = $max_file_size;

$query = new CGI;

if ((scalar $query->param) < 1)
{
   print "invalid body"; # will cause premature header error
   exit;
}

$base_directory = $base_directory . '/' . $query->param('directory') . '/';
$base_directory =~ s{//}{/}g;

foreach $ptmp ($query->param)
{
   if ($ptmp !~ /userfile/)
   {
      next;
   }
   @tmps = $query->param($ptmp);
   @infiles = $query->upload($ptmp);
   $i = 0;
   foreach $tmp (@tmps)
   {
      $infile = $tmps[$i++];
      $tmp =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
      $tmp =~ s/\+/ /sg;
      $tmp =~ s/\\/\//g;
      $tmp =~ s/^\/(.+)$/$1/g;
      $tmp =~ s/\.\././g;
      $filename = $base_directory . $tmp;
      $dir = $filename;
      $dir =~ s/^(.+\/)[^\/]+$/$1/;
      @dirs = split('/', $dir);
      $cur = '';
      foreach $d (@dirs)
      {
         $cur = $cur . $d . '/';
         if ($cur !~ /\/[^\/]+/)
         {
            next;
         }
         mkdir $cur;
         if ($! ne '' && $! ne 'File exists')
         {
            print "could not make dir $cur"; # premature header error
            exit;
         }
      }
      open $outfile, ">$filename";
      binmode $outfile;
      binmode $infile;
      while (<$infile>)
      {
         print $outfile $_;
      }
      close $outfile;
      close $infile;
   }
}

print "Content-Type: text/html\r\n\r\n";
exit;



The Coldfusion example stores the files in the directory '/tmp/files' - you can change this for your own needs to for example 'c://temp/files' for a Windows environment. The code make use of a temporary directory (temp_directory). You can also change this directory.

To download the Coldfusion code click here.
<!--- CHANGE THIS! --->
<!--- The directory where the files will be stored. This directory must be present. --->
<cfset base_directory="/tmp/files">	

<!--- CHANGE THIS! ---> 
<!--- Directory where the files are temporary stored. This directory must be present. --->
<cfset temp_directory="/tmp">

<cfloop index="LoopCount" from="1" to="100000">
  <cfif IsDefined("Form.file_#LoopCount#")>
		
    <!--- Store the file in the temp directory --->
    <cffile action="upload" fileField="file_#LoopCount#" 
          destination="#temp_directory#" nameConflict="overwrite">

    <!--- Retrieve the urldecoded uploaded name, e.g. "images/img001.jpg" --->
    <cfset clientfile=URLDecode(#cffile.clientFile#)>
		
    <!--- Determine the absolute path --->
    <cfif IsDefined("Form.directory")>
      <cfset path=#base_directory# & "/" & #Form.directory# & "/" & #clientfile#>
    <cfelse>
      <cfset path=#base_directory# & "/" & #clientfile#>
    </cfif>

    <cfset dir=GetDirectoryFromPath(#path#)>

    <!--- Create if necessary the directory where the file will be stored. --->
    <cfif not DirectoryExists(#dir#)>
      <cfdirectory action="create" directory="#dir#">
    </cfif>

    <cfset serverPath=#cffile.serverDirectory# & "/" & #cffile.clientFile#>

    <!--- move the file to the final destination --->
    <cffile action="move" source="#serverPath#" destination="#path#">

    <cfelse>
    <cfabort>
  </cfif>
</cfloop>




dot