upload file lewat servlet


yang jadi masalah di java web tuh gak da fasilitas upload otomatis seperti di PHP, heheehe, beruntunglah yang pake php, soalnya mekanisme uploadnnya lebih simpel ๐Ÿ˜ฆ tapi bukan berarti pada developer java hilang akal ๐Ÿ™‚

sekarang hampir 90% programmer java pake Apache Common FileUpload untuk membantu proses uplad, why? ya karena kegampangannya dan simple, pokoknya kerenlah!! ๐Ÿ˜€

nah sekarang gw mo kasih sedikit sourcecode buat upload file lewat servlet pake bantuan apache common fileupload, pertama otomatis buat dulu form uploadnya :


	
		Eko Ganteng
	
	
<h1>Upload File Coy!!!</h1>

			Upload
			
			
		
	

nah habis itu baru bikin servlet buat handler upload filenya :

package echo.gokil.my.servlet;

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

/**
 * Servlet implementation class UploadHandler
 */
public class UploadHandler extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		if (ServletFileUpload.isMultipartContent(request)) {
			FileItemFactory fileItemFactory = new DiskFileItemFactory();
			ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
			try {
				List list = servletFileUpload.parseRequest(request);
				String folder = getServletContext().getRealPath("upload");
				for (FileItem fileItem : list) {
					if (!fileItem.isFormField()) {
						File file = new File(folder, fileItem.getName());
						FileOutputStream fileOutputStream = new FileOutputStream(file);
						fileOutputStream.write(fileItem.get());
						fileOutputStream.close();
					}
				}
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		}
	}
}

coba jalanin, sekarang file yang lo upload ada di directory “upload” :D, gampang kan?

Iklan

42 pemikiran pada “upload file lewat servlet

  1. Ping balik: Belajar JaVa « WAHYU FIGHTER

  2. for (FileItem fileItem : list) {

    kenapa di bagian itu gwe kok incompatible type yah??
    btw, form uploadnya dong. kok gak ada contohnya.
    thx before

      • 1.5 kok. pake netbeans 6.5.
        kalo gw mouse over tulisannya

        incompatible types
        found : java.lang.Object
        required: org.apache.commons.fileupload.FileItem

        librarynya dah pada gwe import. tapi yang error cuma dibagian itu doang..
        help me dunks :(. masi nubi nih di java..

  3. mas echo, mau nanya nih.

    aq kan baru belajar java web akhir2 ini yaitu jsp n servlet dgn tools netbeans.

    yang ingin saya tanyakan adalah bagaimana caranya menjalankan projek tanpa melalui netbeans
    atau

    secara otomatis dapat langsung mengakses browser dan mengetikkan alamat servlet/jsp kita?

  4. Mas, help me…

    kok aku dapet error pas bagian for (FileItem fileItem : list) {

    kode :
    for (FileItem fileItem : list) {
    if (!fileItem.isFormField()) {
    File file = new File(folder, fileItem.getName());
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    fileOutputStream.write(fileItem.get());
    fileOutputStream.close();
    }
    }

    incompatible types
    found : java.lang.Object
    required: org.apache.commons.fileupload.FileItem

    aku pake netbeans 6.5, java 1,6xx

    help me

  5. hi echo it me tejo ,.. msi inget?
    gw lagi focus di netbean platform, pusing soal konsep lookup, action global contex ,node etc.

    cuman karena ada temen yang lagi pusing soal upload, jd gw nimbrung.
    kasus incompatible type kurasa karena type genericnya nggak di sebutin ,..
    spt nya harusnya kayak gini :

    List list = servletFileUpload.parseRequest(request);

    aritnya list adalah List of FileItem, jadi langsung bisa di loop pake for

    still, temen qu bilang bilang , hasil parseRequest itu nggak ada yang type nya fileItem, jadi tetep nggak masuk loop for ,..

    mohon pencerahan lebih lanjut

  6. walah, kok entry htmlnya nggak di escape sih ?

    maksud gw:

    List list>FileItem< = servletFileUpload.parseRequest(request);

  7. tuhkan malah jadi kebalik, ini nih syntax generics yang bener

    List<FileItem> list = servletFileUpload.parseRequest(request);

  8. Ping balik: Tutorial Java dari Eko Kurniawan Khannedy « nge-WP@net

  9. bro kok gw gak bisa dapet items dari upload.parseRequest nya yah, hasil size list nya 0 . Padahal ServletFileUpload.isMultipartContent(request) udah return true . thx be 4

  10. mas echo gw mw nanya nihh…
    mslh upload file ke dlm database via servlet(JPA)..

    source jsp

    upload_test

    Upload File

     
    
                Upload
                 
                 
             
             
       

    ini source servlet

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    package com.sss.servlet.web;

    import com.sss.DocMgmnt.entity.document.Document;
    import java.io.IOException;
    import java.util.List;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.annotation.Resource;
    import javax.management.Query;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileItemFactory;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.eclipse.persistence.config.PessimisticLock;
    import org.eclipse.persistence.config.QueryHints;

    /**
    *
    * @author newbie
    */
    @PersistenceContext(name = “persistence/LogicalName”, unitName = “BankingPU”)
    public class UploadDataServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    @Resource
    private javax.transaction.UserTransaction utx;

    /**
    # * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    # */
    @SuppressWarnings(“unchecked”)

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

    /*Query q = em.createQuery(“SELECT wrf FROM WorkFlow wrf”, WorkFlow.class);

    q.setFirstResult(5);

    q.setMaxResult(100);
    List workflowList = q.getworkflowList();*/

    List documentList = this.findAllDocument();
    documentList.addAll(documentList);

    JSONArray jsonArray = new JSONArray();
    for (int i = 0; i < documentList.size(); i++) {
    JSONObject json = new JSONObject();
    Document document = documentList.get(i);
    if (document.getFilename() == null) {
    json.put("DocumentId", " ");
    } else {
    json.put("DocumentId", document.getDocId());
    }

    if (document.getDocId() == null) {
    json.put("FileName", " ");
    } else {
    json.put("FileName", document.getFilename());
    }
    }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    if (ServletFileUpload.isMultipartContent(request)) {
    FileItemFactory fileItemFactory = new DiskFileItemFactory();
    ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
    try {
    List list = servletFileUpload.parseRequest(request);
    // String folder = getServletContext().getRealPath(“upload”);
    long docId = 0;
    byte[] content = new byte[2 ^ 32];
    for (FileItem fileItem : list) {
    if (fileItem.isFormField()) {
    if (fileItem.getFieldName().equals(“docId”)) {
    docId = Long.parseLong(fileItem.getString());
    }
    } else {
    content = fileItem.get();
    }
    }
    Document document = this.find(docId);
    document.setFilename(content);
    } catch (FileUploadException e) {
    e.printStackTrace();
    }
    }
    }

    protected void persist(Object object) {
    try {
    Context ctx = (Context) new InitialContext().lookup(“java:comp/env”);
    utx.begin();
    EntityManager em = (EntityManager) ctx.lookup(“persistence/LogicalName”);
    em.persist(object);
    utx.commit();
    } catch (Exception e) {
    Logger.getLogger(getClass().getName()).log(Level.SEVERE, “exception caught”, e);
    throw new RuntimeException(e);
    }
    }

    protected void edit(Object object) {
    try {
    Context ctx = (Context) new InitialContext().lookup(“java:comp/env”);
    utx.begin();
    EntityManager em = (EntityManager) ctx.lookup(“persistence/LogicalName”);
    em.merge(object);
    utx.commit();
    } catch (Exception e) {
    Logger.getLogger(getClass().getName()).log(Level.SEVERE, “exception caught”, e);
    throw new RuntimeException(e);
    }
    }

    protected void remove(Object object) {
    try {
    Context ctx = (Context) new InitialContext().lookup(“java:comp/env”);
    utx.begin();
    EntityManager em = (EntityManager) ctx.lookup(“persistence/LogicalName”);
    em.remove(object);
    utx.commit();
    } catch (Exception e) {
    Logger.getLogger(getClass().getName()).log(Level.SEVERE, “exception caught”, e);
    throw new RuntimeException(e);
    }
    }

    protected Document find(long id) {
    try {
    Context ctx = (Context) new InitialContext().lookup(“java:comp/env”);
    // utx.begin();
    EntityManager em = (EntityManager) ctx.lookup(“persistence/LogicalName”);
    return em.find(com.sss.DocMgmnt.entity.document.Document.class, id);
    // utx.commit();
    } catch (Exception e) {
    Logger.getLogger(getClass().getName()).log(Level.SEVERE, “exception caught”, e);
    throw new RuntimeException(e);
    }
    }

    protected List findAllDocument() {
    List documentList = null;
    try {
    Context ctx = (Context) new InitialContext().lookup(“java:comp/env”);
    utx.begin();
    EntityManager em = (EntityManager) ctx.lookup(“persistence/LogicalName”);
    documentList = em.createQuery(“SELECT d FROM Document d”).
    setHint(QueryHints.PESSIMISTIC_LOCK, PessimisticLock.Lock).getResultList();
    utx.commit();
    } catch (Exception e) {
    Logger.getLogger(getClass().getName()).log(Level.SEVERE, “exception caught”, e);
    throw new RuntimeException(e);
    }
    return documentList;
    }

    public List findWithFileName(String Filename) throws NamingException {
    Listfilename = null;
    try {
    Context ctx = (Context) new InitialContext().lookup(“java:comp/env”);
    //utx.begin();
    EntityManager em = (EntityManager) ctx.lookup(“persistence/LogicalName”);
    Query query = (Query) em.createQuery(
    “SELECT d FROM Document d” + “WHERE d.filename = :filename”);
    } catch (NamingException ex) {
    Logger.getLogger(ProjectServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    return filename;
    }

    }

    ini entity’y

    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    package com.sss.DocMgmnt.entity.document;

    import com.sss.DocMgmnt.entity.workflow.WorkFlow;
    import java.io.Serializable;
    import java.util.Date;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Lob;
    import javax.persistence.ManyToOne;
    import javax.persistence.NamedQueries;
    import javax.persistence.NamedQuery;
    import javax.persistence.Table;
    import javax.persistence.Temporal;

    /**
    *
    * @author newbie
    */
    @Entity
    @Table(name=”documents”)
    @NamedQueries({
    @NamedQuery(name = “Document.findBydocId”, query = “SELECT d FROM Document d WHERE d.docId = :docId”),
    @NamedQuery(name =”Document.findByfilename”,query=”SELECT d FROM Document d WHERE d.filename = :filename”)
    })
    public class Document implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long docId;
    @Column(name=”type”, nullable=true)
    private String type;
    @Column(name=”number”, nullable=true)
    private String number;
    @Column(name=”doc_date”, nullable=true)
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date docDate;
    @Column(name=”description”, nullable=true)
    private String description;
    @Column(name=”format”, nullable=true) ///pdf, xls, doc, ods, odt, etc…
    private String format;
    @Column(name=”filename”, length=2^32, nullable=false)
    @Lob
    private byte[] filename;

    @ManyToOne
    private WorkFlow workflow;

    public Long getDocId() {
    return docId;
    }

    public void setDocId(Long docId) {
    this.docId = docId;
    }

    public WorkFlow getWorkflow() {
    return workflow;
    }

    public void setWorkflow(WorkFlow workflow) {
    this.workflow = workflow;
    }

    public String getDescription() {
    return description;
    }

    public void setDescription(String description) {
    this.description = description;
    }

    public Date getDocDate() {
    return docDate;
    }

    public void setDocDate(Date docDate) {
    this.docDate = docDate;
    }

    public byte[] getFilename() {
    return filename;
    }

    public void setFilename(byte[] filename) {
    this.filename = filename;
    }

    public String getFormat() {
    return format;
    }

    public void setFormat(String format) {
    this.format = format;
    }

    public String getNumber() {
    return number;
    }

    public void setNumber(String number) {
    this.number = number;
    }

    public String getType() {
    return type;
    }

    public void setType(String type) {
    this.type = type;
    }

    @Override
    public int hashCode() {
    int hash = 0;
    hash += (docId!= null ? docId.hashCode() : 0);
    return hash;
    }

    @Override
    public boolean equals(Object object) {
    // TODO: Warning – this method won’t work in the case the id fields are not set
    if (!(object instanceof Document)) {
    return false;
    }
    Document other = (Document) object;
    if ((this.docId == null && other.docId != null) || (this.docId != null && !this.docId.equals(other.docId))) {
    return false;
    }
    return true;
    }

    @Override
    public String toString() {
    return “entity.coresyariahbanking.Documents[docId=” + docId + “]”;
    }

    }

    ktika di run smua lancar dan langsung masuk ke hlmn upload.jsp

    tpi ktika saya klick upload kok
    malah ada pesan “The requested resource () is not available”

    kira2 salah’y di mana ya mas..
    tlg ya..?

    mklum gw msi nubie.. ๐Ÿ˜€

    • Saya coba bantu jawab:

      uploadFile yang di action form itu url servlet. nah, supaya program diatas bisa jalan, maka perlu ditambahkan kode di web.xml seperti ini:

      uploadservlet
      echo.gokil.my.servlet.UploadHandler

      uploadservlet
      /uploadFile

  11. mas eko, mohon pencerahan nya..ane ada sedikit permasalahan tentang upload file nih,

    ane pake spring mvc dengan view nya ane pak jsp juga.
    permasalahan ane adalah saat upload, terus waktu ane coba cetak pada bagian.
    List items = upload.parseRequest(request);

    nah value yang ane dapet = [ ]

    mohon pencerahan nya mas,,hehe..

    tks.

  12. kok ga muncul scrip formnya… yah….
    maap maap ane post ulang aja, untuk scrip form nya
    form action=”UploadFoto” method=”post” enctype=”multipart/form-data” name=”form1″ id=”form1″

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s