spring MVC+boottstrap 파일 업로드 예제 구현(진행 막대 포함)

10067 단어 springmvc진도 표
최근 boottstrap 을 배 웠 습 니 다.spring MVC 와 결합 하여 파일 업로드 예 시 를 썼 습 니 다.필 기 를 남 겨 두 고 쓸데없는 말 을 하지 않 고 코드 를 직접 올 렸 습 니 다.
모니터 클래스 FileUploadProgressListener.Java

package com.gpl.web.listener;  
import javax.servlet.http.HttpSession; 
 
import org.apache.commons.fileupload.ProgressListener; 
import org.springframework.stereotype.Component; 
 
import com.gpl.web.utils.Progress; 
 
 
@Component 
public class FileUploadProgressListener implements ProgressListener{ 
 
  private HttpSession session; 
   
  public void setSession(HttpSession session){ 
    this.session = session; 
    Progress status = new Progress(); 
    session.setAttribute("status", status); 
  } 
  @Override 
  public void update(long bytesRead, long contentLength, int items) { 
    Progress status = (Progress) session.getAttribute("status"); 
    status.setBytesRead(bytesRead); 
    status.setContentLength(contentLength); 
    status.setItems(items); 
  } 
 
} 

CustomerMyltipartResolver.java

package com.gpl.web.listener;  
import java.util.List; 
import javax.servlet.http.HttpServletRequest;  
import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileUpload; 
import org.apache.commons.fileupload.FileUploadBase; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.web.multipart.MaxUploadSizeExceededException; 
import org.springframework.web.multipart.MultipartException; 
import org.springframework.web.multipart.commons.CommonsMultipartResolver; 
 
public class CustomMultipartResolver extends CommonsMultipartResolver{ 
   
  @Autowired 
  private FileUploadProgressListener progressListener; 
   
  public void setFileUploadProgressListener(FileUploadProgressListener progressListener){ 
    this.progressListener = progressListener; 
  } 
   
  public MultipartParsingResult parsingResult(HttpServletRequest request){ 
    String encoding = determineEncoding(request); 
    FileUpload fileUpload = prepareFileUpload(encoding); 
    progressListener.setSession(request.getSession()); 
    fileUpload.setProgressListener(progressListener); 
    try{ 
      List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request); 
      return parseFileItems(fileItems, encoding); 
    }catch(FileUploadBase.SizeLimitExceededException ex){ 
      throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex); 
    }catch (FileUploadException e) { 
      throw new MultipartException("  ",e); 
    } 
  } 
 
} 

진도 실체 클래스 Progress.java

package com.gpl.web.utils; 
public class Progress { 
   private long bytesRead; 
  private long contentLength; 
  private long items; 
  public long getBytesRead() { 
    return bytesRead; 
  } 
  public void setBytesRead(long bytesRead) { 
    this.bytesRead = bytesRead; 
  } 
  public long getContentLength() { 
    return contentLength; 
  } 
  public void setContentLength(long contentLength) { 
    this.contentLength = contentLength; 
  } 
  public long getItems() { 
    return items; 
  } 
  public void setItems(long items) { 
    this.items = items; 
  } 
  @Override 
  public String toString() { 
    return "Progress [bytesRead=" + bytesRead + ", contentLength=" + contentLength + ", items=" + items + "]"; 
  } 
   
   
} 

spring 프로필 은 다음 bean 을 추가 해 야 합 니 다.

<!--      --> 
  <bean id="multipartResolver" class="com.gpl.web.listener.CustomMultipartResolver"> 
    <property name="defaultEncoding" value="utf-8"></property> 
    <property name="maxUploadSize" value="838860800"></property> 
  </bean> 

controller 계층 구현

/** 
   *      
   * @param request 
   * @param response 
   * @param file 
   * @throws IOException 
   */ 
  @RequestMapping(value = "/upload", method = RequestMethod.POST) 
  public void upload(HttpServletRequest request,HttpServletResponse response,@RequestParam("file") CommonsMultipartFile file) 
      { 
    try{ 
      PrintWriter out; 
      boolean flag = false; 
      if(file.getSize() > 0){ 
        String path = "/asserts/upload/files/excel/"; 
        String uploadPath = request.getSession().getServletContext().getRealPath(path); 
        System.out.println(uploadPath); 
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(uploadPath,file.getOriginalFilename())); 
        flag = true; 
      } 
      out = response.getWriter(); 
      if(flag == true){ 
        out.print("1"); 
      }else{ 
        out.print("2"); 
      } 
    }catch(Exception e){ 
      e.printStackTrace(); 
    } 
     
  } 

전단 코드

<div id="uploadFileDlg" class="easyui-dialog" style="width:800px;text-align:center;" 
      closed="true"> 
      <form id="uploadFileForm" method="post" style="width:100%;text-align:center;padding:20px 0;"> 
        <input id="file" type="file" style="width:500px;display:inline-block;"> 
        <button id="uploadBtn" class="easyui-linkButton" style="width:auto;display:inline-block;">  </button>  
      </form> 
      <div class="progress progress-bar-striped active" style="display:none;"> 
        <div id="progressBar" class="progress-bar progress-bar-info" role="progressbar" 
        aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" 
        style="width:0%;"> 
        </div> 
      </div> 
      <table id="uploadBatchDg"></table> 
    </div> 
페이지 ready 가입 js 코드

$("#uploadBtn").attr("disabled",false); 
    $("#uploadBtn").click(function(){ 
      var fileValue = $("#file").val(); 
      if(fileValue == null || fileValue == ""){ 
        layer.msg("      "); 
        return; 
      } 
      var obj = $("#file"); 
      var photoExt=obj.val().substr(obj.val().lastIndexOf(".")).toLowerCase();//        
      if(photoExt!=".xls" && photoExt!=".xlsx"){ 
        layer.msg("   xls  xlsx     ,         "); 
        return false; 
      } 
      var fileSize = 0; 
      var isIE = /msie/i.test(navigator.userAgent) && !window.opera;    
      if (isIE && !obj.files) {    
        var filePath = obj.val();    
        var fileSystem = new ActiveXObject("Scripting.FileSystemObject");  
        var file = fileSystem.GetFile (filePath);     
        fileSize = file.Size;    
      }else {  
        fileSize = obj.get(0).files[0].size;   
      }  
      fileSize=Math.round(fileSize/1024*100)/100; //   KB 
      if(fileSize > 5000){ 
        layer.msg("      5M"); 
        return false; 
      } 
      $("#progressBar").width("0%"); 
      $(this).attr("disabled",true); 
      $("#progressBar").parent().show(); 
      $("#progressBar").parent().addClass("active"); 
      uploadFile(); 
파일 업로드 js 코드

function uploadFile() { 
      var fileObj = $("#file").get(0).files[0]; // js        
      console.info("     :"+fileObj); 
      var FileController = "${basePath}/batch/upload"; //              
      // FormData    
      var form = new FormData(); 
      // form.append("author", "hooyes"); //          
      form.append("file", fileObj); //      
      // XMLHttpRequest    
      var xhr = new XMLHttpRequest(); 
      xhr.open("post", FileController, true); 
      xhr.onload = function() { 
        layer.msg("    "); 
        $("#uploadBtn").attr('disabled', false); 
        $("#uploadBtn").val("  "); 
        $("#progressBar").parent().removeClass("active"); 
        $("#progressBar").parent().hide(); 
      }; 
      xhr.upload.addEventListener("progress", progressFunction, false); 
      xhr.send(form); 
    } 
    
    function progressFunction(evt) { 
      var progressBar = $("#progressBar"); 
      if (evt.lengthComputable) { 
        var completePercent = Math.round(evt.loaded / evt.total * 100)+ "%"; 
        progressBar.width(completePercent); 
        $("#uploadBtn").val("     " + completePercent); 
      } 
    }; 

효과 도

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기