原文鏈接:http://blog.csdn.net/qq_37936542/article/details/79258158
jquery file upload是一款實用的上傳文件插件,項目中剛好用到,在這里記錄分享一下。
一:准備相關js文件
jquery file upload 下載地址:點擊打開鏈接 點擊下面紅圈中的按鈕下載
jquery.js下載地址:點擊打開鏈接
二:導入js文件
注意:js文件引入的先后順序不可以亂
- <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
- <!-- jquery file upload相關js -->
- <script src="js/jquery.ui.widget.js"></script>
- <script src="js/jquery.iframe-transport.js"></script>
- <script src="js/jquery.fileupload.js"></script>
- <script src="js/jquery.fileupload-process.js"></script>
- <script src="js/jquery.fileupload-validate.js"></script>
三:jsp代碼
- <style>
- /* input樣式 */
- #uploadImg{
- display: none;
- }
- /* button樣式 */
- #chooseFile{
- background: #93b6fc;
- }
- #uploadFile,#rechooseFile {
- display: none;
- background: #93b6fc;
- }
- #image{
- width:200px;
- height:200px;
- }
- /* 進度條樣式 */
- .bar {
- background-image: -webkit-linear-gradient(top,#5cb85c 0,#449d44 100%);
- background-image: -o-linear-gradient(top,#5cb85c 0,#449d44 100%);
- background-image: -webkit-gradient(linear,left top,left bottom,from(#5cb85c),to(#449d44));
- background-image: linear-gradient(to bottom,#5cb85c 0,#449d44 100%);
- filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0);
- background-repeat: repeat-x;
- height: 20px;
- line-height: 20px;
- -webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
- box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
- -webkit-transition: width .6s ease;
- -o-transition: width .6s ease;
- transition: width .6s ease;
- }
- #progress {
- filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0);
- background-repeat: repeat-x;
- height: 20px;
- width: 0%;
- margin-bottom: 20px;
- overflow: hidden;
- background-color: #f5f5f5;
- border-radius: 4px;
- -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
- box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
- margin-top: 20px;
- }
- </style>
- <body>
- <div class="jquery-fileupload">
- <div class="">
- <input id="uploadImg" type="file" name="uploadImg" multiple style="display: none" />
- <button id="chooseFile">+選擇文件</button>
- <button id="uploadFile">~開始上傳</button>
- <button id="rechooseFile">+重新選擇</button>
- </div>
- <div>
- <img id="image" src="">
- </div>
- <div id="progress">
- <div class="bar" style="width: 0%;"></div>
- </div>
- </div>
- </body>
四:js代碼
- $(function() {
- $("#chooseFile").on("click", function() {
- $("#uploadImg").click();
- });
- $('#uploadImg').fileupload({
- url : '/FileTest/upload',//請求發送的目標地址
- Type : 'POST',//請求方式 ,可以選擇POST,PUT或者PATCH,默認POST
- //dataType : 'json',//服務器返回的數據類型
- autoUpload : false,
- acceptFileTypes : /(gif|jpe?g|png)$/i,//驗證圖片格式
- maxNumberOfFiles : 1,//最大上傳文件數目
- maxFileSize : 1000000, // 文件上限1MB
- minFileSize : 100,//文件下限 100b
- messages : {//文件錯誤信息
- acceptFileTypes : '文件類型不匹配',
- maxFileSize : '文件過大',
- minFileSize : '文件過小'
- }
- })
- //圖片添加完成后觸發的事件
- .on("fileuploadadd", function(e, data) {
- //validate(data.files[0])這里也可以手動來驗證文件格式和大小
- //隱藏或顯示頁面元素
- $('#progress .bar').css(
- 'width', '0%'
- );
- $('#progress').hide();
- $("#chooseFile").hide();
- $("#uploadFile").show();
- $("#rechooseFile").show();
- //獲取圖片路徑並顯示
- var url = getUrl(data.files[0]);
- $("#image").attr("src", url);
- //綁定開始上傳事件
- $('#uploadFile').click(function() {
- $("#uploadFile").hide();
- jqXHR = data.submit();
- //解綁,防止重復執行
- $("#uploadFile").off("click");
- })
- //綁定點擊重選事件
- $("#rechooseFile").click(function(){
- $("#uploadImg").click();
- //解綁,防止重復執行
- $("#rechooseFile").off("click");
- })
- })
- //當一個單獨的文件處理隊列結束觸發(驗證文件格式和大小)
- .on("fileuploadprocessalways", function(e, data) {
- //獲取文件
- file = data.files[0];
- //獲取錯誤信息
- if (file.error) {
- console.log(file.error);
- $("#uploadFile").hide();
- }
- })
- //顯示上傳進度條
- .on("fileuploadprogressall", function(e, data) {
- $('#progress').show();
- var progress = parseInt(data.loaded / data.total * 100, 10);
- $('#progress').css(
- 'width','15%'
- );
- $('#progress .bar').css(
- 'width',progress + '%'
- );
- })
- //上傳請求失敗時觸發的回調函數
- .on("fileuploadfail", function(e, data) {
- console.log(data.errorThrown);
- })
- //上傳請求成功時觸發的回調函數
- .on("fileuploaddone", function(e, data) {
- alert(data.result);
- })
- //上傳請求結束后,不管成功,錯誤或者中止都會被觸發
- .on("fileuploadalways", function(e, data) {
- })
- //手動驗證
- function validate(file) {
- //獲取文件名稱
- var fileName = file.name;
- //驗證圖片格式
- if (!/.(gif|jpg|jpeg|png|gif|jpg|png)$/.test(fileName)) {
- console.log("文件格式不正確");
- return true;
- }
- //驗證excell表格式
- /* if(!/.(xls|xlsx)$/.test(fileName)){
- alert("文件格式不正確");
- return true;
- } */
- //獲取文件大小
- var fileSize = file.size;
- if (fileSize > 1024 * 1024) {
- alert("文件不得大於一兆")
- return true;
- }
- return false;
- }
- //獲取圖片地址
- function getUrl(file) {
- var url = null;
- if (window.createObjectURL != undefined) {
- url = window.createObjectURL(file);
- } else if (window.URL != undefined) {
- url = window.URL.createObjectURL(file);
- } else if (window.webkitURL != undefined) {
- url = window.webkitURL.createObjectURL(file);
- }
- return url;
- }
- });
五:服務器端代碼
1:導入依賴
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.3.1</version>
- </dependency>
2:配置springmvc上傳解析器
- <!-- springmvc文件上傳解析器 -->
- <bean id="multipartResolver"
- class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <property name="defaultEncoding" value="UTF-8" />
- <property name="maxUploadSize" value="-1" />
- </bean>
3:java代碼
- package com.mote.upload;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import javax.servlet.http.HttpServletRequest;
- import org.apache.commons.io.FileUtils;
- import org.springframework.stereotype.Controller;
- 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.bind.annotation.ResponseBody;
- import org.springframework.web.multipart.MultipartFile;
- @Controller
- public class FileUploadController {
- /**
- * 將圖片上傳到服務器根目錄下
- * @param @param multipartFile
- * @param @param request
- * @param @return
- * @return String
- * @throws
- */
- @RequestMapping(value = "/upload",method=RequestMethod.POST)
- @ResponseBody
- public String upload(
- @RequestParam("uploadImg") MultipartFile multipartFile,
- HttpServletRequest request) {
- try {
- //獲取項目路徑
- String realPath = request.getSession().getServletContext()
- .getRealPath("");
- InputStream inputStream = multipartFile.getInputStream();
- String contextPath = request.getContextPath();
- //服務器根目錄的路徑
- String path = realPath.replace(contextPath.substring(1), "");
- //根目錄下新建文件夾upload,存放上傳圖片
- String uploadPath = path + "upload";
- //獲取文件名稱
- String filename = getUploadFileName(multipartFile);
- //將文件上傳的服務器根目錄下的upload文件夾
- File file = new File(uploadPath, filename);
- FileUtils.copyInputStreamToFile(inputStream, file);
- //返回圖片訪問路徑
- String url = request.getScheme() + "://" + request.getServerName()
- + ":" + request.getServerPort() + "/upload/" + filename;
- return url;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 獲取上傳文件的名稱,新文件名為原文件名加上時間戳
- *
- * @param multipartFile
- * multipartFile
- * @return 文件名
- */
- private String getUploadFileName(MultipartFile multipartFile) {
- String uploadFileName = multipartFile.getOriginalFilename();
- String fileName = uploadFileName.substring(0,
- uploadFileName.lastIndexOf("."));
- String type = uploadFileName.substring(uploadFileName.lastIndexOf("."));
- SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
- String timeStr = sdf.format(new Date());
- String name = fileName + "_" + timeStr + type;
- return name;
- }
- }
文末福利:
福利一:前端,Java,產品經理,微信小程序,Python等8G資源合集大放送:https://www.jianshu.com/p/e8197d4d9880
福利二:微信小程序入門與實戰全套詳細視頻教程

領取方式:
如果需要學習視頻,歡迎關注 【編程微刊】微信公眾號,回復【領取資源】一鍵領取以下所有干貨資源,獲取更多有用技術干貨、文檔資料。所有文檔會持續更新,歡迎關注一起成長!