使用Vue實現圖片上傳的三種方式


項目中需要上傳圖片可謂是經常遇到的需求,本文將介紹 3 種不同的圖片上傳方式,在這總結分享一下,有什么建議或者意見,請大家踴躍提出來。

沒有業務場景的功能都是耍流氓,那么我們先來模擬一個需要實現的業務場景。假設我們要做一個后台系統添加商品的頁面,有一些商品名稱、信息等字段,還有需要上傳商品輪播圖的需求。

我們就以Vue、Element-ui,封裝組件為例子聊聊如何實現這個功能。其他框架或者不用框架實現的思路都差不多,本文主要聊聊實現思路。

1.雲儲存

常見的 七牛雲,OSS(阿里雲)等,這些雲平台提供API接口,調用相應的接口,文件上傳后會返回圖片存儲在服務器上的路徑,前端獲得這個路徑保存下來提交給后端即可。此流程處理相對簡單。

主要步驟

  1. 向后端發送請求,獲取OSS配置數據
  2. 文件上傳,調用OSS提供接口
  3. 文件上傳完成,后的文件存儲在服務器上的路徑
  4. 將返回的路徑存值到表單對象中

代碼范例

我們以阿里的 OSS 服務來實現,們試着來封裝一個OSS的圖片上傳組件。

通過element-ui的upLoad組件的 http-request 參數來自定義我們的文件上傳,僅僅使用他組件的樣式,和其他上傳前的相關鈎子(控制圖片大小,上傳數量限制等)。

<template>
 <el-upload
  list-type="picture-card"
  action="''"
  :http-request="upload"
  :before-upload="beforeAvatarUpload">
  <i class="el-icon-plus"></i>
 </el-upload>
</template>
 
<script>
 import {getAliOSSCreds} from '@/api/common' // 向后端獲取 OSS秘鑰信息
 import {createId} from '@/utils' // 一個生產唯一的id的方法
 import OSS from 'ali-oss'
 
 export default {
  name: 'imgUpload',
  data () {
   return {}
  },
  methods: {
   // 圖片上傳前驗證
   beforeAvatarUpload (file) {
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
     this.$message.error('上傳頭像圖片大小不能超過 2MB!')
    }
    return isLt2M
   },
   // 上傳圖片到OSS 同時派發一個事件給父組件監聽
   upload (item) {
    getAliOSSCreds().then(res => { // 向后台發請求 拉取OSS相關配置
     let creds = res.body.data
     let client = new OSS.Wrapper({
      region: 'oss-cn-beijing', // 服務器集群地區
      accessKeyId: creds.accessKeyId, // OSS帳號
      accessKeySecret: creds.accessKeySecret, // OSS 密碼
      stsToken: creds.securityToken, // 簽名token
      bucket: 'imgXXXX' // 阿里雲上存儲的 Bucket
     })
     let key = 'resource/' + localStorage.userId + '/images/' + createId() + '.jpg' // 存儲路徑,並且給圖片改成唯一名字
     return client.put(key, item.file) // OSS上傳
    }).then(res => {
     console.log(res.url)
     this.$emit('on-success', res.url) // 返回圖片的存儲路徑
    }).catch(err => {
     console.log(err)
    })
   }
  }
 }
</script>

  

傳統文件服務器上傳圖片

此方法就是上傳到自己文件服務器硬盤上,或者雲主機的硬盤上,都是通過 formdata 的方式進行文件上傳。具體的思路和雲文件服務器差不多。

主要步驟

  1. 設置服務器上傳路徑、上傳文件字段名、header、data參數等
  2. 上傳成功后,返回服務器存儲的路徑
  3. 返回的圖片路徑存儲到表單提交對象中

代碼示例

此種圖片上傳根據element-ui的upLoad組件只要傳入后端約定的相關字段即可實現,若使用元素js也是生成formdata對象,通過Ajax去實現上傳也是類似的。

這里只做一個簡單的示例,具體請看el-upload組件相文檔就能實現

<template>
 <el-upload
  ref="imgUpload"
  :on-success="imgSuccess"
  :on-remove="imgRemove"
  accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"
  :headers="headerMsg"
  :action="upLoadUrl"
  multiple>
  <el-button type="primary">上傳圖片</el-button>
 </el-upload>
</template>
 
<script>
 import {getAliOSSCreds} from '@/api/common' // 向后端獲取 OSS秘鑰信息
 import {createId} from '@/utils' // 一個生產唯一的id的方法
 import OSS from 'ali-oss'
 
 export default {
  name: 'imgUpload',
  data () {
   return {
     headerMsg:{Token:'XXXXXX'},
     upLoadUrl:'xxxxxxxxxx'
   }
  },
  methods: {
   // 上傳圖片成功
   imgSuccess (res, file, fileList) {
    console.log(res)
    console.log(file)
    console.log(fileList)  // 這里可以獲得上傳成功的相關信息
   }
  }
 }
</script>

  

圖片轉 base64 后上傳

有時候做一些私活項目,或者一些小圖片上傳可能會采取前端轉base64后成為字符串上傳。當我們有這一個需求,有一個商品輪播圖多張,轉base64編碼后去掉data:image/jpeg;base64,將字符串以逗號的形勢拼接,傳給后端。我們如何來實現呢。

1.本地文件如何轉成 base64

我們通過H5新特性 readAsDataURL 可以將文件轉base64格式,輪播圖有多張,可以在點擊后立馬轉base64也可,我是在提交整個表單錢一次進行轉碼加工。

具體步驟

  1. 新建文件封裝 異步 轉base64的方法
  2. 添加商品的時候選擇本地文件,選中用對象保存整個file對象
  3. 最后提交整個商品表單之前進行編碼處理

在這里要注意一下,因為 readAsDataURL 操作是異步的,我們如何將存在數組中的若干的 file對象,進行編碼,並且按照上傳的順序,把編碼后端圖片base64字符串儲存在一個新數組內呢,首先想到的是promise的鏈式調用,可是不能並發進行轉碼,有點浪費時間。我們可以通過循環 async 函數進行並發,並且排列順序。請看 methods 的 submitData 方法

utils.js

export function uploadImgToBase64 (file) {
 return new Promise((resolve, reject) => {
  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = function () { // 圖片轉base64完成后返回reader對象
   resolve(reader)
  }
  reader.onerror = reject
 })
}

  

添加商品頁面 部分代碼

<template>
 <div>
   <el-upload
    ref="imgBroadcastUpload"
    :auto-upload="false" multiple
    :file-list="diaLogForm.imgBroadcastList"
    list-type="picture-card"
    :on-change="imgBroadcastChange"
    :on-remove="imgBroadcastRemove"
    accept="image/jpg,image/png,image/jpeg"
    action="">
    <i class="el-icon-plus"></i>
    <div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過2M</div>
   </el-upload>
   <el-button>submitData</el-button>
 </div>
</template>
 
<script>
 import { uploadImgToBase64 } from '@/utils' // 導入本地圖片轉base64的方法
 
 export default {
  name: 'imgUpload',
  data () {
   return {
    diaLogForm: {
      goodsName:'', // 商品名稱字段
      imgBroadcastList:[], // 儲存選中的圖片列表
      imgsStr:''   // 后端需要的多張圖base64字符串 , 分割
    }
   }
  },
  methods: {
   // 圖片選擇后 保存在 diaLogForm.imgBroadcastList 對象中
   imgBroadcastChange (file, fileList) {
    const isLt2M = file.size / 1024 / 1024 < 2 // 上傳頭像圖片大小不能超過 2MB
    if (!isLt2M) {
     this.diaLogForm.imgBroadcastList = fileList.filter(v => v.uid !== file.uid)
     this.$message.error('圖片選擇失敗,每張圖片大小不能超過 2MB,請重新選擇!')
    } else {
     this.diaLogForm.imgBroadcastList.push(file)
    }
   },
   // 有圖片移除后 觸發
   imgBroadcastRemove (file, fileList) {
    this.diaLogForm.imgBroadcastList = fileList
   },
   // 提交彈窗數據
   async submitDialogData () {
    const imgBroadcastListBase64 = []
    console.log('圖片轉base64開始...')
    // 並發 轉碼輪播圖片list => base64
    const filePromises = this.diaLogForm.imgBroadcastList.map(async file => {
     const response = await uploadImgToBase64(file.raw)
     return response.result.replace(/.*;base64,/, '') // 去掉data:image/jpeg;base64,
    })
    // 按次序輸出 base64圖片
    for (const textPromise of filePromises) {
     imgBroadcastListBase64.push(await textPromise)
    }
    console.log('圖片轉base64結束..., ', imgBroadcastListBase64)
    this.diaLogForm.imgsStr = imgBroadcastListBase64.join()
    console.log(this.diaLogForm)
    const res = await addCommodity(this.diaLogForm)       // 發請求提交表單
    if (res.status) {
     this.$message.success('添加商品成功')
     // 一般提交成功后后端會處理,在需要展示商品地方會返回一個圖片路徑
    }
   },
  }
 }
</script>

  

這樣本地圖片上傳的時候轉base64上傳就完成了。可是輪播圖有可以進行編輯,我們該如何處理呢?一般來說商品增加頁面和修改頁面可以公用一個組件,那么我們繼續在這個頁面上修改。

編輯時我們首先會拉取商品原有數據,進行展示,在進行修改,這時候服務器返回的圖片是一個路徑 http://xxx.xxx.xxx/abc.jpg 這樣,當我們新增一張圖片的還是和上面的方法一樣轉碼即可。可是后端說,沒有修改的圖片也要賺base64轉過來,好吧那就做把。這是一個在線鏈接 圖片,不是本地圖片,怎么做呢?

2. 在線圖片轉base64

具體步驟

utils.js 文件添加在線圖片轉base64的方法,利用canvas

編輯商品,先拉取原來的商品信息展示到頁面

提交表單之前,區分在線圖片還是本地圖片進行轉碼

utils.js

export function uploadImgToBase64 (file) {
 return new Promise((resolve, reject) => {
  function getBase64Image (img) {
   const canvas = document.createElement('canvas')
   canvas.width = img.width
   canvas.height = img.height
   const ctx = canvas.getContext('2d')
   ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
   var dataURL = canvas.toDataURL()
   return dataURL
  }
 
  const image = new Image()
  image.crossOrigin = '*' // 允許跨域圖片
  image.src = img + '?v=' + Math.random() // 清除圖片緩存
  console.log(img)
  image.onload = function () {
   resolve(getBase64Image(image))
  }
  image.onerror = reject
 })
}

 

添加商品頁面 部分代碼

<template>
 <div>
   <el-upload
    ref="imgBroadcastUpload"
    :auto-upload="false" multiple
    :file-list="diaLogForm.imgBroadcastList"
    list-type="picture-card"
    :on-change="imgBroadcastChange"
    :on-remove="imgBroadcastRemove"
    accept="image/jpg,image/png,image/jpeg"
    action="">
    <i class="el-icon-plus"></i>
    <div slot="tip" class="el-upload__tip">只能上傳jpg/png文件,且不超過2M</div>
   </el-upload>
   <el-button>submitData</el-button>
 </div>
</template>
 
<script>
  import { uploadImgToBase64, URLImgToBase64 } from '@/utils'
   
 export default {
  name: 'imgUpload',
  data () {
   return {
    diaLogForm: {
      goodsName:'', // 商品名稱字段
      imgBroadcastList:[], // 儲存選中的圖片列表
      imgsStr:''   // 后端需要的多張圖base64字符串 , 分割
    }
   }
  },
  created(){
    this.getGoodsData()
  },
  methods: {
   // 圖片選擇后 保存在 diaLogForm.imgBroadcastList 對象中
   imgBroadcastChange (file, fileList) {
    const isLt2M = file.size / 1024 / 1024 < 2 // 上傳頭像圖片大小不能超過 2MB
    if (!isLt2M) {
     this.diaLogForm.imgBroadcastList = fileList.filter(v => v.uid !== file.uid)
     this.$message.error('圖片選擇失敗,每張圖片大小不能超過 2MB,請重新選擇!')
    } else {
     this.diaLogForm.imgBroadcastList.push(file)
    }
   },
   // 有圖片移除后 觸發
   imgBroadcastRemove (file, fileList) {
    this.diaLogForm.imgBroadcastList = fileList
   },
   // 獲取商品原有信息
   getGoodsData () {
    getCommodityById({ cid: this.diaLogForm.id }).then(res => {
     if (res.status) {
      Object.assign(this.diaLogForm, res.data)
      // 把 '1.jpg,2.jpg,3.jpg' 轉成[{url:'http://xxx.xxx.xx/j.jpg',...}] 這種格式在upload組件內展示。 imgBroadcastList 展示原有的圖片
      this.diaLogForm.imgBroadcastList = this.diaLogForm.imgsStr.split(',').map(v => ({ url: this.BASE_URL + '/' + v }))
     }
    }).catch(err => {
     console.log(err.data)
    })
   },
   // 提交彈窗數據
   async submitDialogData () {
    const imgBroadcastListBase64 = []
    console.log('圖片轉base64開始...')
    this.dialogFormLoading = true
    // 並發 轉碼輪播圖片list => base64
    const filePromises = this.diaLogForm.imgBroadcastList.map(async file => {
     if (file.raw) { // 如果是本地文件
      const response = await uploadImgToBase64(file.raw)
      return response.result.replace(/.*;base64,/, '')
     } else { // 如果是在線文件
      const response = await URLImgToBase64(file.url)
      return response.replace(/.*;base64,/, '')
     }
    })
    // 按次序輸出 base64圖片
    for (const textPromise of filePromises) {
     imgBroadcastListBase64.push(await textPromise)
    }
    console.log('圖片轉base64結束...')
    this.diaLogForm.imgs = imgBroadcastListBase64.join()
    console.log(this.diaLogForm)
    if (!this.isEdit) { // 新增編輯 公用一個組件。區分接口調用
     const res = await addCommodity(this.diaLogForm)       // 提交表單
     if (res.status) {
      this.$message.success('添加成功')
     }
    } else {
     const res = await modifyCommodity(this.diaLogForm)      // 提交表單
     if (res.status) {
      this.$router.push('/goods/goods-list')
      this.$message.success('編輯成功')
     }
    }
   }
  }
 }
</script>

至此常用的三種圖片上傳方式就介紹完了,轉base64方式一般在小型項目中使用,大文件上傳還是傳統的 formdata或者 雲服務,更合適。但是 通過轉base64方式也使得,在前端進行圖片編輯成為了可能,不需要上傳到服務器就能預覽。主要收獲還是對於異步操作的處理。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM