您好,登錄后才能下訂單哦!
springMVC利用bootstrap實(shí)現(xiàn)一個(gè)文件上傳功能?針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
監(jiān)聽(tīng)器類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); } } }
進(jìn)度實(shí)體類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層實(shí)現(xiàn)
/** * 文件上傳 * @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" closed="true"> <form id="uploadFileForm" method="post" > <input id="file" type="file" > <button id="uploadBtn" class="easyui-linkButton" >上傳</button> </form> <div class="progress progress-bar-striped active" > <div id="progressBar" class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" > </div> </div> <table id="uploadBatchDg"></table> </div>
頁(yè)面ready加入的js代碼
$("#uploadBtn").attr("disabled",false); $("#uploadBtn").click(function(){ var fileValue = $("#file").val(); if(fileValue == null || fileValue == ""){ layer.msg("請(qǐng)先選擇文件"); return; } var obj = $("#file"); var photoExt=obj.val().substr(obj.val().lastIndexOf(".")).toLowerCase();//獲得文件后綴名 if(photoExt!=".xls" && photoExt!=".xlsx"){ layer.msg("請(qǐng)選擇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 獲取文件對(duì)象 console.info("上傳的文件:"+fileObj); var FileController = "${basePath}/batch/upload"; // 接收上傳文件的后臺(tái)地址 // FormData 對(duì)象 var form = new FormData(); // form.append("author", "hooyes"); // 可以增加表單數(shù)據(jù) form.append("file", fileObj); // 文件對(duì)象 // XMLHttpRequest 對(duì)象 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); } };
效果圖
關(guān)于springMVC利用bootstrap實(shí)現(xiàn)一個(gè)文件上傳功能問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。