Spring MVC upload file annotation

Tutorial Spring MVC kali ini adalah bagaimana membuat program upload file ke server, ada dua library apache yang digunakan untuk upload file dengan Spring MVC framework yaitu library commons-fileupload dan library commons-io semua dapat di download di website apache.org

Berikut langkah-langkahnya :

  1. Diasumsikan anda sudah mengenal spring MVC framework, dan sudah terinstall dalam lingkungan kerja anda. penulis menggunakan IDE NetBeans 8.2 dengan server GlassFish 4.x.x
  2. Tambahkan library commons-fileupload dan library commons-io ke dalam direktori web/WEB-INF/lib/
  3. Buat direktori upload file, misal dalam direktori web/uploads
  4. Daftarkan bean multipartResolver dalam file setingan servlet anda (dispatcher-servlet.xml) baris kode berikut ini
    <bean id="multipartResolver"
     class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
    
  5. Buat Model FormUpload

     public class FormUpload {
        MultipartFile multipartFile;
        // konstruktor + setter getter
    
     }
    
  6. Buat UploadController dalam direktori Controller anda, denga kode berikut ini:
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import javax.servlet.ServletContext;
    import org.nf.app.models.FormUpload;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.multipart.MultipartFile;
    
    /**
     *
     * @author rojul
     */
    @Controller
    public class UploadController {
    
        @Autowired
        ServletContext context;
    
        @RequestMapping(value = "/index")
        public String formUpload(Model model) {
            model.addAttribute("aform", new FormUpload());
            return "formUpload";
        }
    
        @RequestMapping(value = "/savefile", method = RequestMethod.POST)
       public String singleSave(@RequestParam("file") MultipartFile file,
                @RequestParam("desc") String desc ,Model model){
    
            String fileName = null;
            if (!file.isEmpty()) {
                try {
                    fileName = file.getOriginalFilename();
                    byte[] bytes = file.getBytes();
    
                    String lokasi_upload = "/uploads";
                    String absolute_file_upload = context.getRealPath(lokasi_upload);
    
                    BufferedOutputStream buffStream
                            = new BufferedOutputStream(new FileOutputStream(
                          new File(absolute_file_upload + File.separator + fileName)));
                    buffStream.write(bytes);
                    buffStream.close();
                    model.addAttribute("filename", fileName);
                    model.addAttribute("pesan", "sukses upload");
    
                } catch (Exception e) {
                    model.addAttribute("pesan", "gagal upload");
    
                }
            } else {
                model.addAttribute("pesan", "file kosong");
            }
    
            return "hasilUpload";
        }
    
    }
    
  7. Buat file formUpload.jsp dengan baris kode pada body program berikut ini:
    <form method="post" enctype="multipart/form-data" action="savefile.htm ">
    		Upload File: <input type="file" name="file">
    		<br /><br />
    		Description: <input type="text" name="desc"/>
    		<br/><br/><input type="submit" value="Upload">
    </form>
    
  8. Dan buat file hasilUpload.jsp untuk menampilkan file gambar hasil upload anda dengan kode berikut ini:
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Page</title>
        </head>
        <body>
            <h1>${pesan}</h1>
    
            <img src="<c:url value="/uploads/${filename}"/>"/>
    
        </body>
    </html>
    

Selamat mencoba !!

Post a Response