拖拽上傳
阿新 • • 發佈:2021-11-01
拖拽上傳檔案
<template> <div ref="drag" class="drag"> <div class="drag-icon-box"> <!-- 採用的是 element-ui 的圖示 --> <i class="el-icon-upload"></i> </div> <div class="drag-message"> <span class="drag-message-title">將檔案拖動到此處,或</span> <label for="file" class="drag-message-label"> <input class="drag-message-input" type="file" id="file" name="file" @change="handleFileChange" /> <span class="drag-message-manual">點選上傳</span> </label> </div> <div> <!-- 採用的是 element-ui 的進度條元件 --> <el-progress :stroke-width="20" :text-inside="true" :percentage="uploadProgress" ></el-progress> </div> </div> </template> <script> export default { data() { return { file: null, upLoadProgress:0//進度條 } }, async mounted() { // 給容器繫結相關的拖拽事件 this.bindEvents() }, methods: { bindEvents() { const drag = this.$refs.drag // 被拖動的物件進入目標容器 drag.addEventListener('dragover', e => { e.preventDefault() drag.style.borderColor = 'red' }) // 被拖動的物件離開目標容器 drag.addEventListener('dragleave', e => { e.preventDefault() drag.style.borderColor = '#eee' }) // 被拖動的物件進入目標容器,釋放滑鼠鍵 drag.addEventListener('drop', e => { e.preventDefault() drag.style.borderColor = '#eee' const fileList = e.dataTransfer.files this.file = fileList[0] this.uploadFile() }) }, async uploadFile() { const form = new FormData() form.append('name', 'file') form.append('file', this.file) const res = await axios.post('/upload', form,{ //axios中onUploadProcess實現 onUploadProgress: progress => { this.uploadProgress = Number( ((progress.loaded / progress.total) * 100).toFixed(2) ) } }) }, handleFileChange(e) { const file = e.target.files[0] if (!file) return this.file = file this.uploadFile() } } } </script> <style lang="scss" scoped> .drag { width: 660px; height: 300px; border: 2px dashed; border-color: #a3a3a3; border-radius: 5px; margin: 0 auto; display: flex; flex-direction: column; justify-content: center; align-items: center; flex-wrap: wrap; .drag-icon-box { width: 100%; height: 60px; text-align: center; font-size: 50px; line-height: 60px; color: #606266; } .drag-message { width: 100%; height: 50px; line-height: 50px; text-align: center; .drag-message-title { font-size: 14px; color: #606266; } .drag-message-label { width: 120px; height: 50px; height: auto; position: relative; overflow: hidden; .drag-message-input { position: absolute; left: -100px; top: -100px; z-index: -1; display: none; } .drag-message-manual { font-size: 14px; color: #4b87ff; cursor: pointer; } } } } </style>
取消上傳事件
利用axios的cancel token進行取消
-
使用CancelToken工廠方法建立cancel token
const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.post('/upload', form, { cancelToken: source.token }) source.cancel();
-
傳遞一個executor函式到CancelToken的建構函式來建立cancel token
const CancelToken = axios.CancelToken; let cancel; axios.post('/upload', form, { cancelToken: new CancelToken(function executor(c) { cancel = c; }) }); cancel();