1. 程式人生 > 程式設計 >Vue實現附件上傳功能

Vue實現附件上傳功能

本文例項為大家分享了Vue實現附件上傳的具體程式碼,供大家參考,具體內容如下

前言

前端 UI 是用的是 element-ui 的上傳功能

本文主要記錄下程式碼,方便下次複製貼上

前端部分

HTML

  • limit: 限制檔案個數 1 個
  • on-remove: 移除附件時的鉤子函式,主要就 console 輸出下
  • on-error: 用於處理上傳異常後的處理,本人這主要用來關閉彈窗和全屏等待
  • file-list: 繫結附件
  • auto-upload: 禁止自動上傳,true 的話選了檔案就自動上傳
  • http-request: 自定義上傳檔案請求方法,預設方法會與 mock 產生 XmlRequest 重新生成導致找不到檔案問題,我註釋了 mock 還是那樣,沒具體研究
  • action: 原上傳檔案的路徑,由於使用了自定義上傳檔案請求,即 http-request,因此這個欄位隨便寫就好,不寫不行好像
<el-upload
 ref="upload"
 :limit="1"
 :on-remove="handleRemove"
 :on-error="onError"
 :file-list="fileList"
 :auto-upload="false"
 :http-request="uploadFile"
 action="https://jsonplaceholder.typicode.com/posts/"
 class="upload-demo">
 <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">支援上傳 {{ strRebuild(fileType) }} 格式,且不超過 {{ fileSize }}M</div>
</el-upload>

JS

import { strRebuild,lastSubstring } from '@/utils/strUtil'
import { message } from '@/utils/message'

export default {
 data() {
 return {
 // 附件列表
 fileList: [],// 允許的檔案型別
 fileType: ['xls','xlsx','pdf','doc','docx','txt','jpg','png','jpeg'],// 執行上傳檔案大小,單位 M
 fileSize: 10,}
 },methods: {
 // 清空表單
 clear() {
 // 清空附件
 this.$refs.upload.clearFiles()
 },// 附件檢查
 // 檢查附件是否屬於可上傳型別
 // 檢查附件是否超過限制大小
 checkFile() {
 var flag = true
 var tip = ''
 var files = this.$refs.upload.uploadFiles
 files.forEach(item => {
 // 檔案過大
 if (item.size > this.fileSize * 1024 * 1024) {
 flag = false
 tip = ' 檔案超過' + this.fileSize + 'M'
 }
 // 檔案型別不屬於可上傳的型別
 if (!this.fileType.includes(lastSubstring(item.name,'.'))) {
 flag = false
 tip = ' 檔案型別不可上傳'
 }
 })
 if (!flag) {
 message('error',tip)
 }
 return flag
 },// 提交附件
 submitUpload() {
 if (this.checkFile()) {
 console.log('上傳附件...')
 this.$refs.upload.submit()
 } else {
 console.log('取消上傳')
 }
 },// 自定義檔案上傳方法
 uploadFile(file) {
 // 把檔案放入 FormData 進行提交
 const param = new FormData()
 param.append('files',file.file)
 uploadFile(param).then(response => {
 // TODO 一些關閉彈框,上傳成功提示等
 })
 },// 移除附件
 handleRemove(file,fileList) {
 console.log('移除附件...')
 },// 附件上傳失敗,列印下失敗原因
 onError(err) {
 message('error','附件上傳失敗')
 console.log(err)
 },// 字串重組
 strRebuild(str) {
 return strRebuild(str)
 }
 }
}

工具類 JS

strUtil.js

// 字串相關工具類
// 陣列根據分隔符重組為字串
export function strRebuild(arr,split) {
 if (arr === undefined || arr === null || !(arr instanceof Array) || arr.length === 0) {
 return ''
 }
 if (split === undefined || split === null) {
 split = ','
 }
 var str = ''
 arr.forEach((v,i) => {
 if (i === arr.length - 1) {
 str = str + v
 } else {
 str = str + v + split
 }
 })
 return str
}

// 擷取最後一個特定字元後面的字串
export function lastSubstring(str,split) {
 if (str === undefined || str === null || split === undefined || split === null) {
 return ''
 }
 return str.substring(str.lastIndexOf(split) + 1)
}

message.js

import { Message } from 'element-ui'

// 提示封裝 type 提示型別, msg 提示資訊,duration 持續時間
export function message(type,msg,duration) {
 Message({
 message: msg || 'success',type: type || 'success',duration: duration || 5 * 1000
 })
}

// 帶刪除鍵提示,duration 為 0 時,不會自動消失
// 提示封裝 type 提示型別, msg 提示資訊,duration 持續時間
export function messageShowClose(type,duration: duration || 0,showClose: true
 })
}

API

// 附件上傳
export function uploadFile(file) {
 return request({
 url: '/uploadFile',method: 'post',headers: {
 'Content-Type': 'multipart/form-data; charset=utf-8'
 },data: file
 })
}

後端介面

/**
 * 單檔案上傳
 * @param files 接收檔案要以陣列接收
 * @return
 */
@PostMapping(value="/uploadFile")
public void uploadFile(@RequestBody MultipartFile[] files) {
 // TODO
}

更多文章可以點選《Vue.js前端元件學習教程》學習閱讀。

關於vue.js元件的教程,請大家點選專題vue.js元件學習教程進行學習。

更多vue學習教程請閱讀專題《vue實戰教程》

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。