Minggu, 17 Agustus 2014

Tutorial aplikasi upload file dengan Spring MVC

Untuk mengikuti tutorial ini, saya sarankan menggunakan Spring Tool Suite (STS).

Berikut langkah-langkah membuat aplikasi upload dengan Spring MVC;

1. Buat project


2. Buat project setting


3. Struktur file/folder terlihat seperti berikut


4. Atur dependencies (penambahan dependency)

5. Karena kita memulai dengan Spring Tool Suite (STS) mengikuti langkah-langkah diatas, maka secara default maka Controller-nya dibuat oleh STS. Ganti Controller seperti code berikut

package com.nitza.tutupload;

import java.util.Locale;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HomeController {
 
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String home() { 
  return "home";
 }
}


6. Buat form dan ganti home.jsp seperti berikut


7. Tambahkan method postFileUpload seperti berikut

package com.nitza.tutupload;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.servlet.ServletContext;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HomeController {
 
 @Autowired
 ServletContext context;
 
 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String home() { 
  return "home";
 }
 
 
 @RequestMapping(value="/fileupload/upload",method=RequestMethod.POST)
 public String postFileUpload(HttpServletRequest request, 
   HttpServletResponse response,
   Model model) 
 {
  
  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  
  List fileNames = new ArrayList(); //upload beberapa file
  
  if (isMultipart) {
   
   FileItemFactory factory = new DiskFileItemFactory(); //membuat FileFactory
   
   ServletFileUpload upload = new ServletFileUpload(factory);
   
   try {
    
    List items = upload.parseRequest(request);
    Iterator iterator = items.iterator();
    
    while (iterator.hasNext()) {
     FileItem item = (FileItem) iterator.next();
     if (!item.isFormField() && !item.getName().equals("")) {
      String fileName = item.getName();
      
      /* jika file upload ditempatkan relatif terhadap folder aplikasi (/resources) 
      String root = context.getRealPath("/");
      File path = new File(root + "/resources");
       */
      
      //berikut ditempatkan relatif terhadap server
      File path = new File("/home/nitza/tututut"); 
      
      if (!path.exists()) {
       boolean status = path.mkdirs(); //jika path tidak ada, maka dibuat oleh aplikasi
      }

      File uploadedFile = new File(path + "/" + fileName);
      fileNames.add(fileName);
      System.out.println("File Path:-"
        + uploadedFile.getAbsolutePath());

      item.write(uploadedFile);
     }
    }
   } catch (FileUploadException e) {
    System.out.println("FileUploadException:- " + e.getMessage());
   } catch (Exception e) {
    System.out.println("Exception:- " + e.getMessage());
   }
      
  }
  
  model.addAttribute("files",fileNames);
  return "view_success";
  
 }
 
}



8. Buat file view_success.jsp seperti berikut


Finish!