logo



Code examples - MyImageUploader
MyImageUploader runs in a browser. The image uploader uploads the images from the browser to your web server. On the server you need to have a script / program that accepts the uploaded images and saves the files on hard drive of the server. This script can be build with ASP.NET, C#, Java and PHP. Below you will find examples of these scripts.
Base code examples

yes PHP
yes Java Servlet
yes Java JSP
yes ASP.NET
yes C#

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.

The maximum default file upload size of PHP is 2MB. If you want to upload larger images than you need to change the following settings in 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 = "/tmp";
$target_directory = "";

if (isset($_REQUEST["directory"])) {
  $target_directory = $base_directory . "/" . $_REQUEST["directory"] . "/";
} else {
  $target_directory = $base_directory . "/";
}

// create the subfolder
mkdir($target_directory, 0777, true);

// be sure that the folder has the right permissions
chmod($target_directory, 0777);

if (!file_exists($target_directory) || !is_writable($target_directory)) {
  error_log("Problem with the upload directory: " . $target_directory);
  header("HTTP/1.0 500 Internal Server Error");
  exit;
}

// save the thumbnail
$error = $_FILES["thumbfile"]["error"];

if ($error == UPLOAD_ERR_OK) {

  $path = $target_directory . $_FILES["thumbfile"]["name"];
	
  if(move_uploaded_file($_FILES["thumbfile"]["tmp_name"], $path)) {
    chmod($path, 0666);
  } else {
    error_log("File: " . $path . " cannot be saved.");		
  }	
} else {
  error_log("An error has occurred with the thumbnail: " . $error);		
}

// save the source file
$error = $_FILES["sourcefile"]["error"];

if ($error == UPLOAD_ERR_OK) {

  $path = $target_directory . $_FILES["sourcefile"]["name"];
	
  if(move_uploaded_file($_FILES["sourcefile"]["tmp_name"], $path)) {
    chmod($path, 0666);
  } else {
    error_log("File: " . $path . " cannot be saved.");
    header("HTTP/1.0 500 Internal Server Error");
    exit;
  }
	
} else {

  error_log("An error has occurred with the source file: " . $error);
  header("HTTP/1.0 500 Internal Server Error");
  exit;
}
?>



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.

package uploadserver;

import java.io.File;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

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

  /**
   * The base upload directory. In this directory all uploaded files will
   * be stored. 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
    // in 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 {

            File file = new File(directory, item.getName());
            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 uploaded images in the directory '/tmp' - you can change this if you like, to for example 'c://temp' for a Windows environment.

<%@ 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
// in other words check that the http request can have uploaded images
if (isMultipart) {

  // The base upload directory. In this directory all uploaded files will
  // be stored. For a Windows environment the base directory can be e.g. 
  // 'c:/temp' for Linux environment '/tmp'.
  String baseDirectory = "/tmp";

  // 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 {

        File file = new File(directory, item.getName());
        file = new File(baseDirectory, 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.

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 folders As String
    Dim PostedFile As HttpPostedFile

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

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

      PostedFile = Request.Files(i)

      ' Creates the full path
      Dim filePath As String = Path.Combine(folders, PostedFile.FileName)   

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

      ' Save the uploaded file
      PostedFile.SaveAs(filePath)

    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, 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>



dot