[Tutorial] Upload File dan Isi Form Sederhana ke Database dengan JSP

Karena banyak pertanyaan terkait insert isi form ke database dan upload image / file ke server, akhirnya gw memutuskan untuk nulis ini di blog gw, kali aja suatu saat ada yang nanya lagi.

Disini gw bikin aplikasi sederhana dengan 1 input text dan 1 input untuk upload file, semua yang diinput akan masuk ke database. Khusus untuk si file akan masuk path relatifnya (image/NamaImageYangDiUpload). Gw pakek library apache commons fileupload, commons io dan Hibernate framework (pake query sql biasa juga bisa tapi gw males aja, ahhahaaa).

oke langsung aja, gw bikin table sederhana banget,

CREATE TABLE upload
(
    id INT NOT NULL AUTO_INCREMENT,
    uploadBy VARCHAR(20) NOT NULL,
    imagePath VARCHAR(200) NOT NULL,
    PRIMARY KEY (id)
)

java bean ma hbm.xml-nya

package com.baculsoft.bean;

public class Upload  implements java.io.Serializable {


     private Integer id;
     private String uploadBy;
     private String imagePath;

    public Upload() {
    }

    public Upload(String uploadBy, String imagePath) {
       this.uploadBy = uploadBy;
       this.imagePath = imagePath;
    }
   
    // other setter and getter

    @Override
    public String toString() {
        return "Upload{" + "id=" + id + " uploadBy=" + uploadBy + " imagePath=" + imagePath + '}';
    }

}
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.baculsoft.bean.Upload" table="upload" catalog="test">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="uploadBy" type="string">
            <column name="uploadBy" length="20" not-null="true" />
        </property>
        <property name="imagePath" type="string">
            <column name="imagePath" length="50" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

lalu hibernate.cfg.xml buat handle koneksi ke database

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">password</property>
    <property name="hibernate.connection.autocommit">true</property>
    <mapping resource="com/baculsoft/bean/Upload.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

dan file java buat ngeload hibernate.cfg.xml

package com.baculsoft.hbm;


import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author edw
 */
public class HiberUtil {
    private static final SessionFactory sessionFactory;

    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

nah ini adalah JSP gw, coba perhatiin kalo gw punya 2 input type. 1 buat input dengan type text 1 lagi buat input type file.

<%-- 
    Document   : index
    Created on : Jan 2, 2011, 9:34:34 PM
    Author     : edw
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>        
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <form action="upload" method="POST" enctype="multipart/form-data">
            Input Your Name : <input type="text" name="uploadBy" />
            <br />
            Select file : <input type="file" name="fileSelect" />
            <br />
            <input type="submit" />
        </form>
    </body>
</html>

nah, yang rada ribet ada disini. Ini adalah servlet yg gw bikin khusus buat handle transfer file dari client ke server dan save path+nama file tersebut ke database. Method yg gw gunakan untuk insert ke database ada di line 90.

package com.baculsoft.servlet;

import com.baculsoft.bean.Upload;
import com.baculsoft.hbm.HiberUtil;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.hibernate.Session;

public class UploadServlet extends HttpServlet {

    private Logger logger = Logger.getLogger(UploadServlet.class);

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String uploadTo = getServletContext().getRealPath("/") + "image/";

        try {
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            // no multipart form
            if (!isMultipart) {
                out.println("<html>");
                out.println("<head>");
                out.println("<title>Servlet UploadServlet</title>");
                out.println("</head>");
                out.println("<body>");
                out.println("<h1>No Multipart Files</h1>");
                out.println("</body>");
                out.println("</html>");
            }
            // multipart form
            else {
                // Create a new file upload handler
                ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());

                // parse requests
                List<FileItem> fileItems = servletFileUpload.parseRequest(request);

                // open session factory
                Session session = HiberUtil.getSessionFactory().openSession();

                // prepare upload bean
                Upload upload = new Upload();

                // Process the uploaded items
                for (FileItem fileItem : fileItems) {                    
                    
                    // a regular form field
                    if (fileItem.isFormField()) {

                        // disini sama dengan nama input text field di index.jsp yaitu "uploadBy"
                        if(fileItem.getFieldName().equalsIgnoreCase("uploadBy")){
                            upload.setUploadBy(fileItem.getString());
                        }
                    }
                    // upload field
                    else {
                        String fileName = fileItem.getName();
                        File fileTo = new File(uploadTo + fileName);
                        fileItem.write(fileTo);

                        out.println("<html>");
                        out.println("<head>");
                        out.println("<title>Servlet UploadServlet</title>");
                        out.println("</head>");
                        out.println("<body>");
                        out.println("<h1> success write to " + fileTo.getAbsolutePath() + "</h1>");
                        out.println("</body>");
                        out.println("</html>");

                        // set uploaded file's location
                        upload.setImagePath("image/"+fileName);

                    }
                }

                session.save(upload);

                session.flush();
                session.close();

                logger.debug("success");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        } finally {
            out.close();
        }
    }
   
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}

berikut adalah log4j.properties gw

# Global logging configuration
log4j.rootLogger=DEBUG,stdout

# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%c{1}] %-5p %c:%L - %m%n

ini struktur project netbeans gw,

ini lib yg gw pakek

File yang berhasil terupload akan disimpan di folder image/. Disini gw coba upload 2 kali.

dan ini isi database gw

Silahkan dicoba masing-masing yeh, :-[

Google+

27 Comments

arif

about 6 years ago

tutorialnya mantab! ada yang bahasa inggris pula , lengkap juga... haha!! makasih sudah membantu (Y)

Reply

edwin

about 6 years ago

anytime arif, makasih udh berkunjung. Jangan lupa kalo udh berhasil kamu bantu temen-temen kamu yg lain yah. :)

riky

about 5 years ago

source codenya gan upload plisssssss :) ini mantabs banget tau

Reply

edwin

about 5 years ago

ok siap bro, ini gw baru bikin id github soalnya moga2 minggu ini bisa gw upload sourcenya :D

Rio

about 5 years ago

gan klo nampilinnya gimana yah? ane udah coba pake tag src tapi ga muncul. pdahal file pathnya sesuai. :-S

Reply

edwin

about 5 years ago

alow bro Rio, kalo filenya image, loe bisa display langsung pakek img src, kalo selain image di panggil langsung via a href. Oh iya, pathnya adalah path di browser yah, bukan path di window explorer.

Ade Hapli

about 5 years ago

Gan.. ane udah ketik semuanya.. database komplit.. compile g ada yang error.. tpi pas di running file gambarnya g ke upload.. :-S apanya yg kurang sih gan.. :-O mohon pencerahannya.. atau klo agan bisa.. kasih ane project yg jadinya deh biar ane g bingung.. :-( Saya ucapkan Terima kasih atas perhatiannya.. :-)

Reply

Ade Hapli

about 5 years ago

Initial SessionFactory creation failed.org.hibernate.MappingException: element in configuration specifies no attributes pesan errornya kyk diatas gan.. apa yang salah y.. mohon petunjuknya.. Thx...

Reply

Ade Hapli

about 5 years ago

maaf gan... ane udah berhasil uploadnya.. thx y gan atas tutornya.. (Y) :-D

Reply

edwin

about 5 years ago

Hi Ade, mantab dah :D

Exneval

about 5 years ago

Mas Edwin, file sudah berhasil terupload tetapi tidak ada penambahan database, kira kira kendalanya dimana ya ? Kalau saya boleh tau dimana letak konfigurasi table mysql nya, saya lihat tidak ada sama sekali..

Reply

edwin

about 5 years ago

hi Exneval, konfigurasi koneksi ke mysql ada di file hibernate.cfg.xml :)

Exneval

about 5 years ago

Oh, ternyata saya lupa mengedit nama database di hibernate mappingnya, trims mas Edwin, tutorialnya sangat berguna

Reply

diang

about 5 years ago

selamat pagi mas ku mau bikin sebuah aplikasi yang mengupload sebuah file ke website apa ini sama seperti tutorial yang mas buat hanya dirubah letak dimana kita akan upload file tersebut ya ??? tolong pencerahannya terima kasih

Reply

edwin

about 4 years ago

Hi Diang, harusnya sih bisa jadi sama, mungkin hanya lokasi upload file yg berbeda

andi rachmansyah

about 4 years ago

mau tanya mas edwin, ketika running project pada netbeans muncul comment seperti ini, solusinya seperti apa ya? mohon pencerahannya mas : "F:\Documents and Settings\Andi Rachmansyah\Desktop\Library chart\TemperatureMonitoring\nbproject\build-impl.xml:312: The following error occurred while executing this line: java.io.FileNotFoundException: F:\Documents and Settings\Andi Rachmansyah\Desktop\Library chart\BelajarJFreeChart\build.xml (The system cannot find the path specified) BUILD FAILED (total time: 0 seconds)"

Reply

edwin

about 4 years ago

Hi Andi, build.xml-nya ada engga? Coba create ulang project Netbeans-nya

Welda Aprilia

about 4 years ago

misi kak mau nanya hbm.xml-nya ditaro dimana ya?

Reply

edwin

about 4 years ago

Hi Welda, hbm.xml dibawah package java, di sreenshot diatas kan ada tu :D

Welda Aprilia

about 4 years ago

HTTP Status 404 – /IniResepkuApaResepmu/upload type Status report message /IniResepkuApaResepmu/upload description The requested resource (/IniResepkuApaResepmu/upload) is not available. kalo kaya gitu kenapa ya kak? mohon bantuannya

Reply

edwin

about 4 years ago

Hi Welda, kayaknya ada yg error tu coba periksa stacktrace aplikasinya

Asagi

about 3 years ago

Mas Edwin mohon bantuannya . klu mau upload file csv kemudian nampilin terlebih dahulu sebelum di simpan ke dalam database , intinya gini gue punya file csv inisnya itu file data ampilute dan time mau di upload dulu ke web browser kemudian nanti data itu mau di analisis then disimpan ke dalam database.skrng saya gunakan netbeans IDE 7.4 "java servlet / java web application"

Reply

edwin

about 3 years ago

Hi Asagi, bisa aja sih, kamu pakek javascript, save ke table temporary kalo uploadnya udah sukses, tinggal panggil ajax ke table temporary tersebut. ga terlalu sulit kok :D

iman

about 2 years ago

kak, itu periksa stacktracenya gimana yaa . aku juga ngalamain hal kaya gitu. terus itu yang di file uploadservlet.java kan ada tanda kunci yaa . itu ngaruh ngga ? soalnya aku ngga ada

Reply

edwin

about 2 years ago

Hi iman, tanda kunci yg mana yah?

choirul

about 2 years ago

mas tipe data yang dipakai pada database gambarnya itu pakai tipe data apa ?

Reply

edwin

about 2 years ago

Halo Choirul, aku pakai varchar untuk menampung nama image hasil upload

Leave a Comment

Please be polite. We appreciate that.
Your email address will not be published and required fields are marked


:-[ (B) (^) (P) (@) (O) (D) :-S ;-( (C) (&) :-$ (E) (~) (K) (I) (L) (8) :-O (T) (G) (F) :-( (H) :-) (*) :-D (N) (Y) :-P (U) (W) ;-)