spring MVC+boottstrap 파일 업로드 예제 구현(진행 막대 포함)
모니터 클래스 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);
}
};
효과 도이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
springmvc application/octet-stream problemmistake: Source code: Solution: Summarize: application/octet-stream is the original binary stream method. If the convers...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.