Skip to main content

JSP/Servlet File Upload....

Wah dah lama juga ga posting... jadi gue sempet mikir kira-kira enaknya posting apa ya?
nah kebetulan beberapa waktu yang lampau gue pernah dapet assignment dari kantor untuk buat aplikasi yang mengupload file zip lewat JSP/Servlet trus waktu selesai di upload file tadi langsung otomatis diextract... nah... pada posting kali ini gue pengen ngebahas gimana caranya buat Script upload file di JSP/Servlet... karena umumnya penanganan request yang bersifat multi-part agak berbeda pada server j2ee container dibandingkan dengan bahasa pemograman lainnya (eg. PHP). bagi yang belum ngerti atau ngga' bisa java tapi pingin belajar silahkan comment disini, nanti gue buat post tentang "java tutorial"

berikut adalah beberapa API yang harus dimiliki terlebih dahulu.
  1. download API commons-fileupload disini
  2. download API commons-io disini
setelah file telah didownload kita lanjutkan dengan coding... pertama kali yang harus dilakukan adalah memasukkan API library diatas kedalam classpath atau dimasukan kedalam library di IDE favorit masing-masing, bagi yang belum tau caranya silahkan googling dulu...

untuk menambahkan library ke IDE NetBeans bisa lihat gambar berikut ini



setelah API di load dalam classpath yang pertama kali harus dilakukan dalam membuat script adalah mengimport paket-paket standar bawaan commons-fileupload dan commons-io

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

berikut adalah kode lengkapnya
package com.shido.uploader;

import java.io.File;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import javax.servlet.http.HttpServletRequest;
/**
 *
 * @author shido
 */
public class Uploader {
    private HttpServletRequest request;
    public Uploader(HttpServletRequest request){
        this.request = request;
    }
    public Hashtable upload() throws Exception {
        return upload("UploadFiles/");
    }
    public Hashtable upload(String uploadPath) throws Exception {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // maximum size that will be stored in memory
        factory.setSizeThreshold(4096);
        // the location for saving data that is larger than getSizeThreshold()
        factory.setRepository(new File(uploadPath));

        ServletFileUpload upload = new ServletFileUpload(factory);
        // maximum size before a FileUploadException will be thrown
        upload.setSizeMax(5000000);
        List fileItems = upload.parseRequest(request);
        // assume we know there are two files. The first file is a small
        // text file, the second is unknown and is written to a file on
        // the server
        Iterator i = fileItems.iterator();
        Hashtable table = new Hashtable();
        while (i.hasNext()) {
            FileItem fi = (FileItem) i.next();
            // filename on the client
            if (!fi.isFormField()) {
                String fileName = fi.getName();
                // save comment and filename to database

                String fieldName = fi.getFieldName();

                // write the file
                File file = new File(uploadPath + fileName.substring(fileName.lastIndexOf(File.pathSeparator)+1));
                if(file.exists()){
                    throw new Exception("Filename already exist in server! Rename or choose different file!");
                }
                fi.write(file);
                table.put(fieldName, file.getName());
            }else{
                table.put(fi.getFieldName(), fi.getString());
            }
        }
        return table;
    }
}


bersambung...

Comments

HERLoct_HENT said…
Jiah, kok pake bersambung segala aniki... Yang lengkapnya mana???
Anonymous said…
wahh koq bersambung...
padahal udah smangat..
mana kelanjutanx??

Popular posts from this blog

The Future Of Computing is Ubuntu Phone

As we are know, in the beginning of January 2013. Canonical announce their new project called Ubuntu Phone. From the beginning Ubuntu was just another Linux distro,  but now Canonical driving Ubuntu far beyond its beginnings as just another Linux distro into an Operating System that works on  television and even being  an android and iPhone competitor, Ubuntu is skating to where they puck is going to be. But, which such a bold move, there are significant obstacles to overcome. The soon to be released Ubuntu Phone is paving the way that all smart phones will eventually go. Back to the late  1943 where  computers were gigantic, filling rooms and requiring constant care and maintenance. Over time, the components required to build the computers become smaller and cheaper, till eventually it was possible to put one on your desk until the laptop computer, a smaller, more portable, but just as powerful machine was made and make it nearly obsolete. And then, com...

Ubuntu 9.04 x86_64 Run well in Acer Aspire 4530

Hey guys, after a while I didn't update this blog, right now I'm just feeling like to share my happiness. Just want to inform you all that ubuntu 9.04 64bit run well in my laptop... i'm just happy to say to my self welcome back to ubuntu after a while back to windows because ubuntu version lesser than 9.04 doesn't support my laptop. the installation process is simple, much more simple than before. to install ubuntu 9.04 please follow this steps: insert ubutu 9.04 live CD or the alternate version of it set your optical drive as your first boot device at BIOS or press F12 at boot sequence to select which device you want to boot from. select install ubuntu to harddrive wait until boot process done and setup your storage partition (at least 1 ext3/ext4 partition and 1 swap partition fill your name, user name and password. wait until installation progress finished. reboot you laptop now. VIOLA! your ubuntu now ready to use okay let's check so...