vue-element-admin自帶上傳圖片組件,在使用的過程當中發現上傳速度很慢,尤爲是上傳一些大圖須要耗時幾十秒不能忍受。出現這種狀況,是由於upload組件會將圖片上傳到action="https://httpbin.org/post"
,並返回轉換成base64編碼格式的數據。css
格式相似:vue
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAIBAQEBAQIBAQECAgICAgQDAgICAgUEBAMEBgUGBgYFBgYGBwkIBgcJBwYGCAsIC.....
並且有可能這個base64編碼比上傳源文件還要大。git
這樣作有兩個缺點:github
還有一點就這種是必須圖片和表單其餘內容一塊兒提交,有的時候上傳和表單其餘項分開提交。golang
接下來說一下如何將圖片單獨上傳到服務的實現步驟:web
具體代碼在如下項目裏數據庫
https://github.com/guyan0319/...json
https://gitee.com/jason0319/g...api
vue-element-admin\src\utils\global.js
內容以下服務器
const httphost = 'http://localhost:8090' export { httphost }
這個是服務端的地址,能夠根據須要本身調整。
引入上面定義的服務器地址
import { httphost } from '@/utils/global'
data()增長uploadUrl
data() { return { tempUrl: '', uploadUrl: httphost + '/upload/image', dataObj: { token: '', key: '' } } },
將
action=``"https://httpbin.org/post"
修改成
:action="uploadUrl"
圖片上傳成功on-success綁定的handleImageSuccess函數增長了res,即服務端返回上傳結果。
修改代碼以下
handleImageSuccess(res, file) { if (res.code !== 20000){ this.$message({ message: '上傳失敗', type: 'error', showClose: true }) return false } this.emitInput(res.data) },
服務端返回的json格式爲
{ "code":20000, "data":"http://localhost:8090/showimage?imgname=upload/20200620/tX5vS810l2Fl0K02I0YJLEjLEw9OH7hc.jpg" }
這裏須要注意el-upload增長
:with-credentials='true'
支持發送 cookie 憑證信息,上傳文件到服務器端須要判斷驗證登陸。
經過以上修改實現上傳圖片,接下處理上傳文件刪除
文件api/article.js 增長
export function delImage(url) { return request({ url: '', method: 'get', params: { url }, baseURL: httphost + '/del/image' }) }
修改SingleImage3.vue
//引入delImage import { delImage } from '@/api/article'
rmImage() { delImage(this.value).then(response => { if (response.code === 20000){ this.emitInput('') return } this.$message({ message: '刪除失敗', type: 'error', showClose: true }) }).catch(err => { console.log(err) }) },
服務端刪除文件返回json
{"code":20000,"data":"success"}
最後貼一下SingleImage3.vue修改後完整的代碼
<template> <div class="upload-container"> <el-upload :data="dataObj" :multiple="false" :show-file-list="false" :with-credentials='true' :on-success="handleImageSuccess" class="image-uploader" drag :action="uploadUrl" > <i class="el-icon-upload" /> <div class="el-upload__text"> 將文件拖到此處,或<em>點擊上傳</em> </div> </el-upload> <div class="image-preview image-app-preview"> <div v-show="imageUrl.length>1" class="image-preview-wrapper"> <img :src="imageUrl"> <div class="image-preview-action"> <i class="el-icon-delete" @click="rmImage" /> </div> </div> </div> <div class="image-preview"> <div v-show="imageUrl.length>1" class="image-preview-wrapper"> <img :src="imageUrl"> <div class="image-preview-action"> <i class="el-icon-delete" @click="rmImage" /> </div> </div> </div> </div> </template> <script> import { getToken } from '@/api/qiniu' import { delImage } from '@/api/article' import { httphost } from '@/utils/global' // import { Cookies } from 'js-cookie' export default { name: 'SingleImageUpload3', props: { value: { type: String, default: '' } }, data() { return { tempUrl: '', uploadUrl: httphost + '/upload/image', dataObj: { token: '', key: '' } } }, computed: { imageUrl() { return this.value } }, methods: { rmImage() { delImage(this.value).then(response => { if (response.code === 20000){ this.emitInput('') return } this.$message({ message: '刪除失敗', type: 'error', showClose: true }) }).catch(err => { console.log(err) }) }, emitInput(val) { this.$emit('input', val) }, handleImageSuccess(res, file) { if (res.code !== 20000){ this.$message({ message: '上傳失敗', type: 'error', showClose: true }) return false } this.emitInput(res.data) }, beforeUpload() { const _self = this return new Promise((resolve, reject) => { getToken().then(response => { const key = response.data.qiniu_key const token = response.data.qiniu_token _self._data.dataObj.token = token _self._data.dataObj.key = key this.tempUrl = response.data.qiniu_url resolve(true) }).catch(err => { console.log(err) reject(false) }) }) } } } </script> <style lang="scss" scoped> @import "~@/styles/mixin.scss"; .upload-container { width: 100%; position: relative; @include clearfix; .image-uploader { width: 35%; float: left; } .image-preview { width: 200px; height: 200px; position: relative; border: 1px dashed #d9d9d9; float: left; margin-left: 50px; .image-preview-wrapper { position: relative; width: 100%; height: 100%; img { width: 100%; height: 100%; } } .image-preview-action { position: absolute; width: 100%; height: 100%; left: 0; top: 0; cursor: default; text-align: center; color: #fff; opacity: 0; font-size: 20px; background-color: rgba(0, 0, 0, .5); transition: opacity .3s; cursor: pointer; text-align: center; line-height: 200px; .el-icon-delete { font-size: 36px; } } &:hover { .image-preview-action { opacity: 1; } } } .image-app-preview { width: 320px; height: 180px; position: relative; border: 1px dashed #d9d9d9; float: left; margin-left: 50px; .app-fake-conver { height: 44px; position: absolute; width: 100%; // background: rgba(0, 0, 0, .1); text-align: center; line-height: 64px; color: #fff; } } } </style>
須要修改vue-element-adminsrccomponentsTinymcecomponentsEditorImage.vue文件,處理方式和示例一差很少,這裏只貼代碼
<template> <div class="upload-container"> <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary" @click=" dialogVisible=true"> upload </el-button> <el-dialog :visible.sync="dialogVisible"> <el-upload :multiple="true" :file-list="fileList" :show-file-list="true" :with-credentials='true' :on-remove="handleRemove" :on-success="handleSuccess" :before-upload="beforeUpload" class="editor-slide-upload" :action="uploadUrl" list-type="picture-card" > <el-button size="small" type="primary"> Click upload </el-button> </el-upload> <el-button @click="dialogVisible = false"> Cancel </el-button> <el-button type="primary" @click="handleSubmit"> Confirm </el-button> </el-dialog> </div> </template> <script> // import { getToken } from 'api/qiniu' import { delImage } from '@/api/article' import { httphost } from '@/utils/global' export default { name: 'EditorSlideUpload', props: { color: { type: String, default: '#1890ff' } }, data() { return { dialogVisible: false, uploadUrl: httphost + '/upload/image', listObj: {}, fileList: [] } }, methods: { checkAllSuccess() { return Object.keys(this.listObj).every(item => this.listObj[item].hasSuccess) }, handleSubmit() { const arr = Object.keys(this.listObj).map(v => this.listObj[v]) if (!this.checkAllSuccess()) { this.$message('Please wait for all images to be uploaded successfully. If there is a network problem, please refresh the page and upload again!') return } this.$emit('successCBK', arr) this.listObj = {} this.fileList = [] this.dialogVisible = false }, handleSuccess(response, file) { const uid = file.uid const objKeyArr = Object.keys(this.listObj) for (let i = 0, len = objKeyArr.length; i < len; i++) { if (this.listObj[objKeyArr[i]].uid === uid) { this.listObj[objKeyArr[i]].url = response.data // this.listObj[objKeyArr[i]].url = response.files.file this.listObj[objKeyArr[i]].hasSuccess = true return } } }, handleRemove(file) { const uid = file.uid const objKeyArr = Object.keys(this.listObj) for (let i = 0, len = objKeyArr.length; i < len; i++) { if (this.listObj[objKeyArr[i]].uid === uid) { delImage(this.listObj[objKeyArr[i]].url).then(response => { if (response.code !== 20000) { this.$message('刪除失敗') return } delete this.listObj[objKeyArr[i]] }).catch(err => { console.log(err) }) return } } }, beforeUpload(file) { const _self = this const _URL = window.URL || window.webkitURL const fileName = file.uid this.listObj[fileName] = {} return new Promise((resolve, reject) => { const img = new Image() img.src = _URL.createObjectURL(file) img.onload = function() { _self.listObj[fileName] = { hasSuccess: false, uid: file.uid, width: this.width, height: this.height } } resolve(true) }) } } } </script> <style lang="scss" scoped> .editor-slide-upload { margin-bottom: 20px; /deep/ .el-upload--picture-card { width: 100%; } } </style>
至此,vue-element-admin 單獨上傳圖片實現方式就講完了,若有任何問題或建議歡迎提issues,