017_Upload上传
1. Upload上傳
1.1. 通過點擊或者拖拽上傳文件。
1.2. Upload上傳屬性
| 參數 | 說明 | 類型 | 可選值 | 默認值 |
| action | 必選參數, 上傳的地址 | string | 無 | 無 |
| headers | 設置上傳的請求頭部 | object | 無 | 無 |
| multiple | 是否支持多選文件 | boolean | 無 | 無 |
| data | 上傳時附帶的額外參數 | object | 無 | 無 |
| name | 上傳的文件字段名 | string | 無 | file |
| with-credentials | 支持發送cookie憑證信息 | boolean | 無 | false |
| show-file-list | 是否顯示已上傳文件列表 | boolean | 無 | true |
| drag | 是否啟用拖拽上傳 | boolean | 無 | false |
| accept | 接受上傳的文件類型(thumbnail-mode 模式下此參數無效) | string | 無 | 無 |
| on-preview | 點擊文件列表中已上傳的文件時的鉤子 | function(file) | 無 | 無 |
| on-remove | 文件列表移除文件時的鉤子 | function(file, fileList) | 無 | 無 |
| on-success | 文件上傳成功時的鉤子 | function(response, file, fileList) | 無 | 無 |
| on-error | 文件上傳失敗時的鉤子 | function(err, file, fileList) | 無 | 無 |
| on-progress | 文件上傳時的鉤子 | function(event, file, fileList) | 無 | 無 |
| on-change | 文件狀態改變時的鉤子, 添加文件、上傳成功和上傳失敗時都會被調用 | function(file, fileList) | 無 | 無 |
| before-upload | 上傳文件之前的鉤子, 參數為上傳的文件, 若返回false或者返回Promise且被reject, 則停止上傳。 | function(file) | 無 | 無 |
| before-remove | 刪除文件之前的鉤子, 參數為上傳的文件和文件列表, 若返回false或者返回Promise且被reject, 則停止刪除。 | function(file, fileList) | 無 | 無 |
| list-type | 文件列表的類型 | string | text/picture/picture-card | text |
| auto-upload | 是否在選取文件后立即進行上傳 | boolean | 無 | true |
| file-list | 上傳的文件列表, 例如: [{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}] | array | 無 | [] |
| http-request | 覆蓋默認的上傳行為, 可以自定義上傳的實現 | function | 無 | 無 |
| disabled | 是否禁用 | boolean | 無 | false |
| limit | 最大允許上傳個數 | number | 無 | 無 |
| on-exceed | 文件超出個數限制時的鉤子 | function(files, fileList) | 無 | 無 |
1.3. Slot
| name | 說明 |
| trigger | 觸發文件選擇框的內容 |
| tip | 提示說明文字 |
1.4. Methods
| 方法名 | 說明 | 參數 |
| clearFiles | 清空已上傳的文件列表(該方法不支持在before-upload中調用) | 無 |
| abort | 取消上傳請求 | (file: fileList中的file對象) |
| submit | 手動上傳文件列表 | 無 |
2. Upload上傳例子
2.1. 使用腳手架新建一個名為element-ui-upload的前端項目, 同時安裝Element插件。
2.2. 編寫index.js?
import Vue from 'vue' import VueRouter from 'vue-router' import UploadFunction from '../components/UploadFunction.vue' import DragUpload from '../components/DragUpload.vue' import ThumbnailUpload from '../components/ThumbnailUpload.vue' import SubmitUpload from '../components/SubmitUpload.vue'Vue.use(VueRouter)const routes = [{ path: '/', redirect: '/UploadFunction' },{ path: '/UploadFunction', component: UploadFunction },{ path: '/DragUpload', component: DragUpload },{ path: '/ThumbnailUpload', component: ThumbnailUpload },{ path: '/SubmitUpload', component: SubmitUpload } ]const router = new VueRouter({routes })export default router2.3. 在components在新建UploadFunction.vue
<template><div><h1>點擊上傳</h1><h4>通過action設置上傳的地址, 并且action必選參數。</h4><h4>通過file-list上傳的文件列表, 默認是[]數組。</h4><h4>通過limit設置最大允許上傳個數。</h4><h4>通過list-type設置文件列表的類型, 可以設置為text/picture/picture-card, 默認是text。</h4><h4>通過multiple設置是否支持多選文件。</h4><h4>通過show-file-list設置是否顯示已上傳文件列表, 默認為true。</h4><h4>通過accept設置接受上傳的文件類型, 前端并沒有絕對限制。</h4><h4>before-upload上傳文件之前的鉤子, 參數為上傳的文件, 若返回false或者返回Promise且被reject, 則停止上傳。</h4><h4>on-change文件狀態改變時的鉤子, 添加文件、上傳成功和上傳失敗時都會被調用。</h4><h4>on-progress文件上傳時的鉤子。</h4><h4>on-success文件上傳成功時的鉤子。</h4><h4>on-error文件上傳失敗時的鉤子。</h4><h4>on-preview點擊文件列表中已上傳的文件時的鉤子。</h4><h4>before-remove刪除文件之前的鉤子, 參數為上傳的文件和文件列表, 若返回false或者返回Promise且被reject, 則停止刪除。</h4><h4>on-remove文件列表移除文件時的鉤子。</h4><h4>on-exceed文件超出個數限制時的鉤子。</h4><h4>通過slot你可以傳入自定義的上傳按鈕類型和文字提示。</h4><el-upload :action="action2" :file-list="fileList" :limit="limit" list-type="text" multiple :show-file-list="true" accept=".png, .jpg":before-upload="handleBeforeUpload":on-change="handleChange":on-progress="handleProgress":on-success="handleSuccess":on-error="handleError":on-preview="handlePreview":before-remove="beforeRemove":on-remove="handleRemove":on-exceed="handleExceed"><el-button size="small" type="primary">點擊上傳</el-button><div slot="tip" class="el-upload__tip">只能上傳jpg/png文件, 且不超過200MB。</div></el-upload></div> </template><script> export default {data () {return {action1: 'http://localhost:8080/ElementUIUpload/EUpload.action',action2: 'http://localhost:9876/upload',fileList: [],limit: 3}},methods: {handleBeforeUpload (file) {console.log('---handleBeforeUpload---')console.log(file)},handleChange (file, fileList) {console.log('---handleChange---')console.log(file)console.log(fileList)},handleProgress (event, file, fileList) {console.log('---handleProgress---')console.log(event)console.log(file)console.log(fileList)},handleSuccess (response, file, fileList) {console.log('---handleSuccess---')console.log(response)console.log(file)console.log(fileList)},handleError (err, file, fileList) {console.log('---handleError---')console.log(err)console.log(file)console.log(fileList)},handlePreview (file) {console.log('---handlePreview---')console.log(file)},beforeRemove (file, fileList) {console.log('---beforeRemove---')console.log(file)console.log(fileList)return this.$confirm(`確定移除 ${file.name}?`)},handleRemove (file, fileList) {console.log('---handleRemove---')console.log(file)console.log(fileList)},handleExceed (files, fileList) {console.log('---handleExceed---')console.log(files)console.log(fileList)this.$message.warning(`當前限制選擇${this.limit}個文件, 本次選擇了${files.length}個文件, 共選擇了${files.length + fileList.length}個文件`)}} } </script>2.4. 在components在新建DragUpload.vue
<template><div><h1>拖拽上傳</h1><h4>通過drag設置是否啟用拖拽上傳。</h4><el-upload :action="action2" drag list-type="picture"><i class="el-icon-upload"></i><div class="el-upload__text">將文件拖到此處, 或<em>點擊上傳</em></div><div class="el-upload__tip" slot="tip">只能上傳jpg/png文件, 且不超過200MB。</div></el-upload></div> </template><script> export default {data () {return {action1: 'http://localhost:8080/ElementUIUpload/EUpload.action',action2: 'http://localhost:9876/upload'}} } </script>2.5. 在components在新建ThumbnailUpload.vue
<template><div><h1>文件縮略圖</h1><h4>使用scoped-slot去設置縮略圖模版。</h4><el-upload :action="action2" list-type="picture-card" ref="upload"><i class="el-icon-plus"></i><div slot="file" slot-scope="{file}"><img class="el-upload-list__item-thumbnail" :src="file.url" alt=""><span class="el-upload-list__item-actions"><span class="el-upload-list__item-preview" @click="handlePreview(file)"><i class="el-icon-zoom-in"></i></span><span class="el-upload-list__item-delete" @click="handleRemove(file)"><i class="el-icon-delete"></i></span></span></div></el-upload><el-dialog :visible.sync="dialogVisible"><img width="100%" :src="dialogImageUrl" alt=""></el-dialog></div> </template><script> export default {data () {return {action1: 'http://localhost:8080/ElementUIUpload/EUpload.action',action2: 'http://localhost:9876/upload',dialogImageUrl: '',dialogVisible: false}},methods: {handlePreview (file) {this.dialogImageUrl = file.urlthis.dialogVisible = true},handleRemove (file) {var uploadFiles = this.$refs.upload.uploadFilesuploadFiles.filter(function (value, index, array) {if (value.uid === file.uid) {uploadFiles.splice(index, 1)}})}} } </script>2.6. 在components在新建SubmitUpload.vue
<template><div><h1>手動上傳</h1><h4>auto-upload是否在選取文件后立即進行上傳。</h4><h4>trigger觸發文件選擇框的內容。</h4><el-upload ref="upload" :action="action2" :auto-upload="false"><el-button slot="trigger" size="small" type="primary">選取文件</el-button><el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上傳到服務器</el-button><div slot="tip" class="el-upload__tip">只能上傳jpg/png文件, 且不超過200MB。</div></el-upload></div> </template><script> export default {data () {return {action1: 'http://localhost:8080/ElementUIUpload/EUpload.action',action2: 'http://localhost:9876/upload'}},methods: {submitUpload () {this.$refs.upload.submit()}} } </script>3. Servlet上傳文件服務器
3.1. 新建一個名為ElementUIUpload動態web服務器項目
3.2. 新建UFilter.java, 設置跨域訪問?
package com.bjbs;import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse;public class UFilter implements Filter {@Overridepublic void init(FilterConfig config) throws ServletException {System.out.println("在服務器加載項目的時候創建, 初始化。");}@Overridepublic void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {System.out.println("進入到過濾器了, 可以進行過濾操作了。");// 本過濾器放行, 你可以去下一個過濾器或者Servlet了chain.doFilter(request, response);HttpServletResponse res = (HttpServletResponse) response;// 設置跨域訪問/* 允許跨域的主機地址 */res.setHeader("Access-Control-Allow-Origin", "*");/* 允許跨域的請求方法GET, POST, HEAD 等 */res.setHeader("Access-Control-Allow-Methods", "*");/* 重新預檢驗跨域的緩存時間 (s) */res.setHeader("Access-Control-Max-Age", "4200");/* 允許跨域的請求頭 */res.setHeader("Access-Control-Allow-Headers", "*");/* 是否攜帶cookie */res.setHeader("Access-Control-Allow-Credentials", "true");}@Overridepublic void destroy() {System.out.println("服務器停止或者移除項目的時候的銷毀。");} }3.3. 新建EUpload.java上傳文件
package com.bjbs;import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.tomcat.util.http.fileupload.FileItem; import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;public class EUpload extends HttpServlet {private static final long serialVersionUID = 1L;// 上傳文件存儲目錄private static final String UPLOAD_DIRECTORY = "upload";// 上傳配置private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MBprivate static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MBprivate static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// 檢測是否為多媒體上傳if (!ServletFileUpload.isMultipartContent(req)) {// 如果不是則停止PrintWriter writer = resp.getWriter();writer.println("Error: 表單必須包含 enctype=multipart/form-data");writer.flush();return;}// 配置上傳參數DiskFileItemFactory factory = new DiskFileItemFactory();// 設置內存臨界值 - 超過后將產生臨時文件并存儲于臨時目錄中factory.setSizeThreshold(MEMORY_THRESHOLD);// 設置臨時存儲目錄factory.setRepository(new File(System.getProperty("java.io.tmpdir")));ServletFileUpload upload = new ServletFileUpload(factory);// 設置最大文件上傳值upload.setFileSizeMax(MAX_FILE_SIZE);// 設置最大請求值 (包含文件和表單數據)upload.setSizeMax(MAX_REQUEST_SIZE);// 中文處理upload.setHeaderEncoding("UTF-8");// 構造臨時路徑來存儲上傳的文件// 這個路徑相對當前應用的目錄String uploadPath = req.getServletContext().getRealPath("./") + File.separator + UPLOAD_DIRECTORY;// 如果目錄不存在則創建File uploadDir = new File(uploadPath);if (!uploadDir.exists()) {uploadDir.mkdir();}String msg = "上傳文件失敗";try {// 解析請求的內容提取文件數據List<FileItem> formItems = upload.parseRequest(new ServletRequestContext(req));if (formItems != null && formItems.size() > 0) {// 迭代表單數據for (FileItem item : formItems) {// 處理不在表單中的字段if (!item.isFormField()) {String fileName = new File(item.getName()).getName();String filePath = uploadPath + File.separator + fileName;File storeFile = new File(filePath);// 在控制臺輸出文件的上傳路徑System.out.println(filePath);// 保存文件到硬盤item.write(storeFile);}}msg = "文件上傳成功";}} catch (Exception ex) {msg = ex.getMessage();}// 不管是字節流還是字符流, 直接使用一行代碼就可以解決響應亂碼問題。resp.setContentType("text/html;charset=UTF-8");resp.getWriter().print(msg);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }3.4. 在web.xml中, 配置過濾器和Servlet
3.5. 新建index.html, 使用vue和element-ui, 使用upload組件?
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>上傳文件</title><!-- 引入樣式 --><link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"><!-- 引入Vue --><script src="https://lib.baomitu.com/vue/2.6.14/vue.common.dev.js"></script><!-- 引入組件庫 --><script src="https://unpkg.com/element-ui/lib/index.js"></script></head><body><div id="app"><el-upload action="http://localhost:9876/upload" :file-list="fileList" :on-success="handleSuccess" :on-error="handleError"><el-button size="small" type="primary">點擊上傳</el-button></el-upload></div><script>new Vue({el: '#app',data: {fileList: []},methods: {handleSuccess (response, file, fileList) {console.log('---handleSuccess---')console.log(response)console.log(file)console.log(fileList)},handleError (err, file, fileList) {console.log('---handleError---')console.log(err)console.log(file)console.log(fileList)}}})</script></body> </html>4. SpringBoot上傳文件服務器
4.1. 新建一個名為element-upload-spring-boot的SpringBoot項目
4.2. 配置pom.xml?
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>1.5.13.RELEASE</version></parent><groupId>com.bjbs</groupId><artifactId>element-upload-spring-boot</artifactId><version>0.0.1-SNAPSHOT</version><properties><!-- 修改jdk版本 --><java.version>1.8</java.version><!-- 指定thymeleaf和thymeleaf-layout-dialect高版本可以防止html標簽不規范報錯 --><thymeleaf.version>3.0.2.RELEASE</thymeleaf.version><thymeleaf-layout-dialect.version>2.0.4</thymeleaf-layout-dialect.version></properties><dependencies><!-- springBoot的啟動器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- thymeleaf的啟動器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency></dependencies></project>4.3. 新建CorsConfig.java, 支持跨域訪問
package com.bjbs.config;import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;@Configuration public class CorsConfig extends WebMvcConfigurerAdapter {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods("GET", "POST", "DELETE", "PUT").maxAge(3600);} }4.4. 新建UploadController.java
package com.bjbs.controller;import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest;@RestController public class UploadController {@RequestMapping(value="/upload")public Map<String, Object> upload(HttpServletRequest req) {Map<String, Object> map = new HashMap<String, Object>();// 構造臨時路徑來存儲上傳的文件// 這個路徑相對當前應用的目錄String uploadPath = req.getServletContext().getRealPath("./") + File.separator + "upload";// 如果目錄不存在則創建File file = new File(uploadPath);if (!file.exists()) {file.mkdir();}MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();for (Map.Entry<String, MultipartFile> entry : fileMap.entrySet()) {MultipartFile multipartFile = entry.getValue();String fileName = multipartFile.getOriginalFilename();String filePath = uploadPath + File.separator + fileName;try {multipartFile.transferTo(new File(filePath));map.put(fileName, filePath);} catch (IllegalStateException | IOException e) {e.printStackTrace();map.put("msg", e.getMessage());return map;}}map.put("msg", "success");return map;} }4.5. 新建App.java
package com.bjbs;import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication public class App {public static void main(String[] args) {SpringApplication.run(App.class, args);} }4.6. 在src/main/resources下, 配置application.properties
server.port=9876 #設置單個上傳文件的大小 spring.http.multipart.maxFileSize=200MB #設置一次請求上傳文件的總容量 spring.http.multipart.maxRequestSize=1000MB4.7. 在src/main/resources下, 新建static文件夾, 在static文件夾下新建index.html, 使用vue和element-ui, 使用upload組件
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>上傳文件</title><!-- 引入樣式 --><link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"><!-- 引入Vue --><script src="https://lib.baomitu.com/vue/2.6.14/vue.common.dev.js"></script><!-- 引入組件庫 --><script src="https://unpkg.com/element-ui/lib/index.js"></script></head><body><div id="app"><el-upload action="http://localhost:9876/upload" :file-list="fileList" :on-success="handleSuccess" :on-error="handleError"><el-button size="small" type="primary">點擊上傳</el-button></el-upload></div><script>new Vue({el: '#app',data: {fileList: []},methods: {handleSuccess (response, file, fileList) {console.log('---handleSuccess---')console.log(response)console.log(file)console.log(fileList)},handleError (err, file, fileList) {console.log('---handleError---')console.log(err)console.log(file)console.log(fileList)}}})</script></body> </html>5. 允許項目, 上傳文件
5.1. 啟動名為element-upload-spring-boot的SpringBoot項目
5.2. 啟動前端element-ui-upload, 訪問http://localhost:8080/#/UploadFunction, 上傳圖片?
5.3. 前端訪問http://localhost:8080/#/DragUpload, 拖拽上傳圖片?
5.4. 前端訪問http://localhost:8080/#/ThumbnailUpload, 上傳圖片查看大圖?
5.5. 前端訪問http://localhost:8080/#/SubmitUpload, 手動上傳圖片?
總結
以上是生活随笔為你收集整理的017_Upload上传的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 014_TimePicker时间选择器
- 下一篇: 020_Transfer穿梭框