Servlet 3 – Upload File


Pada artikel ini saya akan membahas tentang cara upload file (berkas) menggunakan Servlet 3. Saat ini upload file selalu digunakan pada jenis website apapun, seperti upload gambar photo profile, upload dokumen, dan lain-lain.

Untuk melakukan upload, kita perlu membuat sebuah halaman dengan form input yang menggunakan metode POST dan enctype-nya multipart/form-data, contoh :

<!doctype html>
<html>
    <head>
        <title>Upload File</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <form name="uploadform" action="UploadFile" method="POST" enctype="multipart/form-data">
            <input type="file" name="upload"/>
            <input type="submit" value="Upload"/>
        </form>
    </body>
</html>

Setelah itu, kita dapat membuat halaman Servlet 3 untuk menangani upload data file tersebut :

package khannedy.web.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet(name = "UploadFile", urlPatterns = {"/UploadFile"})
public class UploadFileServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Part part = req.getPart("upload");

        String temp = part.getHeader("content-disposition").split(";")[2].trim();
        String filename = temp.substring("filename=\"".length(), temp.length() - 1);

        InputStream inputStream = part.getInputStream();
        FileOutputStream stream = new FileOutputStream(getServletContext().getRealPath("upload") + "/" + filename);

        int i = -1;
        while ((i = inputStream.read()) != -1) {
            stream.write(i);
        }

        stream.close();
        inputStream.close();

        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        try {
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet SayHelloServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<a href=\"upload/" + filename + "\">");
            out.println("Download Here");
            out.println("</a>");
            out.println("</body>");
            out.println("</html>");
        } finally {
            out.close();
        }
    }
}

hasilnya :

Screenshot-Upload File - Google Chrome

Screenshot-Upload File - Google Chrome

Screenshot-Servlet SayHelloServlet - Google Chrome

Screenshot-Servlet SayHelloServlet - Google Chrome

Iklan

2 pemikiran pada “Servlet 3 – Upload File

  1. kang kayaknya kurang anotasi @MultipartConfig + filename nya di substring lagi filename.substring(filename.lastIndexOf(“\\”),filename.length()) . tapi kenapa yah rada lama uploadnya,, kalo dibandingin sama extensi upload dari apache “FileUpload”.. btw thx tutornya hehe

  2. mohon pencerahan masih ada error :
    java.lang.NullPointerException
    UploadFileServlet.doPost(UploadFileServlet.java:33)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

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