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

Penjualan PSVita Menurun Dijepang

PlayStation 3, sebuah konsol game yang diusung raksasa elekronik asal negeri sakura ini sedang mengalami masa-masa menyenangkan dilihat dari penjualannya yang terus meningkat dibeberapa minggu dibulan ini. Namun hal ini tidak terjadi pada konsol game portabel PSVita yang sama-sama buatan Sony. Penjualan PSVita dalam beberapa minggu ini terus mengalami penurunan yang membuat kondisi ini menjadi suatu berita baik sekaligus buruk bagi Sony. Hal ini diperkuat oleh grafik penjualan yang dibuat oleh beberapa media Jepang yang isinya mencakup tentang penjualan kedua konsol game tersebut dari tanggal 27 Februari hingga 4 Maret. Dalam grafik tersebut menunjukan prestasi PlayStation 3 sebagai pemenang besar di segmen perangkat keras dengan penjualan sebesar 65,116 unit pada kurun waktu tersebut. Sony juga diindikasikan telah berhasil menjual PS3 hampir 2.5x lebih banyak dari minggu sebelumnya... Penjualan hardware yang kuat ini oleh beberapa media jepang dipicu oleh peluncuran piranti...

It's been a while...

It's been a while since my last blog entry. Maybe this time I'll try to write something into this blog. Something about computer and programming related or something other than that. And for all my reader (is there any?), I want to tell you my appreciation and my best regards... Thank You..