文件上傳的 2 套方案
基于文件流(form-data)
element-ui 框架的上傳組件降铸,就是默認(rèn)基于文件流的续室。
- 數(shù)據(jù)格式:form-data;
- 傳遞的數(shù)據(jù): file 文件流信息虎敦;filename 文件名字
客戶端把文件轉(zhuǎn)換為 base64
通過 fileRead.readAsDataURL(file)
轉(zhuǎn)為 base64 字符串后,要用 encodeURIComponent
編譯再發(fā)送政敢, 發(fā)送的數(shù)據(jù)經(jīng)由 qs.stringify
處理其徙,請(qǐng)求頭添加 "Content-Type": "application/x-www-form-urlencoded"
大文件上傳
首先借助 element-ui 搭建下頁(yè)面。因?yàn)橐远x一個(gè)上傳的實(shí)現(xiàn)喷户,所以 el-upload
組件的 auto-upload
要設(shè)定為 false
唾那;action
為必選參數(shù),此處可以不填值褪尝。
<template>
<div id="app">
<!-- 上傳組件 -->
<el-upload action drag :auto-upload="false" :show-file-list="false" :on-change="handleChange">
<i class="el-icon-upload"></i>
<div class="el-upload__text">將文件拖到此處闹获,或<em>點(diǎn)擊上傳</em></div>
<div class="el-upload__tip" slot="tip">大小不超過 200M 的視頻</div>
</el-upload>
<!-- 進(jìn)度顯示 -->
<div class="progress-box">
<span>上傳進(jìn)度:{{ percent.toFixed() }}%</span>
<el-button type="primary" size="mini" @click="handleClickBtn">{{ upload | btnTextFilter}}</el-button>
</div>
<!-- 展示上傳成功的視頻 -->
<div v-if="videoUrl">
<video :src="videoUrl" controls />
</div>
</div>
</template>
復(fù)制代碼
獲取到文件對(duì)象并轉(zhuǎn)成 ArrayBuffer 對(duì)象
轉(zhuǎn)成 ArrayBuffer 是因?yàn)楹竺嬉?SparkMD5 這個(gè)庫(kù)生成 hash 值,對(duì)文件進(jìn)行命名
async handleChange(file) {
const fileObj = file.raw
try{
const buffer = await this.fileToBuffer(fileObj)
console.log(buffer)
}catch(e){
console.log(e)
}
}
復(fù)制代碼
打印 buffer 結(jié)果如下圖
注意:before-upload 函數(shù)和 on-change 函數(shù)的參數(shù)都有 file河哑,但是 on-change 中的 file 不是 File 對(duì)象昌罩,要獲取File 對(duì)象需要通過 file.raw。 這里用到 FileReader 類將 File 對(duì)象轉(zhuǎn) ArrayBuffer 對(duì)象灾馒,因?yàn)槭钱惒竭^程茎用,所以用 Promise 封裝:
// 將 File 對(duì)象轉(zhuǎn)為 ArrayBuffer
fileToBuffer(file) {
return new Promise((resolve, reject) => {
const fr = new FileReader()
fr.onload = e => {
resolve(e.target.result)
}
fr.readAsArrayBuffer(file)
fr.onerror = () => {
reject(new Error('轉(zhuǎn)換文件格式發(fā)生錯(cuò)誤'))
}
})
}
復(fù)制代碼
創(chuàng)建切片
可以通過固定大小或是固定數(shù)量把一個(gè)文件分成好幾個(gè)部分,為了避免由于 js 使用的 IEEE754 二進(jìn)制浮點(diǎn)數(shù)算術(shù)標(biāo)準(zhǔn)可能導(dǎo)致的誤差,我決定用固定大小的方式對(duì)文件進(jìn)行切割轨功,設(shè)定每個(gè)切片的大小為 2M旭斥,即 2M = 21024KB = 21024*1024B = 2097152B。切割文件用到的是 Blob.slice()
// 將文件按固定大泄沤А(2M)進(jìn)行切片垂券,注意此處同時(shí)聲明了多個(gè)常量
const chunkSize = 2097152,
chunkList = [], // 保存所有切片的數(shù)組
chunkListLength = Math.ceil(fileObj.size / chunkSize), // 計(jì)算總共多個(gè)切片
suffix = /\.([0-9A-z]+)$/.exec(fileObj.name)[1] // 文件后綴名
// 根據(jù)文件內(nèi)容生成 hash 值
const spark = new SparkMD5.ArrayBuffer()
spark.append(buffer)
const hash = spark.end()
// 生成切片,這里后端要求傳遞的參數(shù)為字節(jié)數(shù)據(jù)塊(chunk)和每個(gè)數(shù)據(jù)塊的文件名(fileName)
let curChunk = 0 // 切片時(shí)的初始位置
for (let i = 0; i < chunkListLength; i++) {
const item = {
chunk: fileObj.slice(curChunk, curChunk + chunkSize),
fileName: `${hash}_${i}.${suffix}` // 文件名規(guī)則按照 hash_1.jpg 命名
}
curChunk += chunkSize
chunkList.push(item)
}
console.log(chunkList)
復(fù)制代碼
選擇一個(gè)文件后將打印得到諸如下圖的結(jié)果
發(fā)送請(qǐng)求
發(fā)送請(qǐng)求可以是并行的或是串行的羡滑,這里選擇串行發(fā)送菇爪。每個(gè)切片都新建一個(gè)請(qǐng)求,為了能實(shí)現(xiàn)斷點(diǎn)續(xù)傳柒昏,我們將請(qǐng)求封裝到函數(shù) fn
里凳宙,用一個(gè)數(shù)組 requestList
來保存請(qǐng)求集合,然后封裝一個(gè) send
函數(shù)职祷,用于請(qǐng)求發(fā)送氏涩,這樣一旦按下暫停鍵,可以方便的終止上傳有梆,代碼如下:
sendRequest() {
const requestList = [] // 請(qǐng)求集合
this.chunkList.forEach(item => {
const fn = () => {
const formData = new FormData()
formData.append('chunk', item.chunk)
formData.append('filename', item.fileName)
return axios({
url: '/single3',
method: 'post',
headers: { 'Content-Type': 'multipart/form-data' },
data: formData
}).then(res => {
if (res.data.code === 0) { // 成功
if (this.percentCount === 0) {
this.percentCount = 100 / this.chunkList.length
}
this.percent += this.percentCount // 改變進(jìn)度
}
})
}
requestList.push(fn)
})
let i = 0 // 記錄發(fā)送的請(qǐng)求個(gè)數(shù)
const send = async () => {
// if ('暫停') return
if (i >= requestList.length) {
// 發(fā)送完畢
return
}
await requestList[i]()
i++
send()
}
send() // 發(fā)送請(qǐng)求
},
復(fù)制代碼
axios 部分也可以直接寫成下面這種形式:
axios.post('/single3', formData, {
headers: { 'Content-Type': 'multipart/form-data' }
})
復(fù)制代碼
所有切片發(fā)送成功后
根據(jù)后端接口需要再發(fā)送一個(gè) get 請(qǐng)求并把文件的 hash 值傳給服務(wù)器是尖,我們定義一個(gè) complete
方法來實(shí)現(xiàn),這里假定發(fā)送的為視頻文件
const complete = () => {
axios({
url: '/merge',
method: 'get',
params: { hash: this.hash }
}).then(res => {
if (res.data.code === 0) { // 請(qǐng)求發(fā)送成功
this.videoUrl = res.data.path
}
})
}
復(fù)制代碼
這樣就能在文件發(fā)送成功后在頁(yè)面瀏覽到發(fā)送的視頻了泥耀。
斷點(diǎn)續(xù)傳
首先是暫停按鈕文字的處理饺汹,用了一個(gè)過濾器,如果 upload
值為 true
則顯示“暫吞荡撸”兜辞,否則顯示“繼續(xù)”:
filters: {
btnTextFilter(val) {
return val ? '暫停' : '繼續(xù)'
}
}
復(fù)制代碼
當(dāng)按下暫停按鈕,觸發(fā) handleClickBtn
方法
handleClickBtn() {
this.upload = !this.upload
// 如果不暫停則繼續(xù)上傳
if (this.upload) this.sendRequest()
}
復(fù)制代碼
在發(fā)送切片的 send
方法的開頭添加 if (!this.upload) return
陨囊,這樣只要 upload
這個(gè)變量為 false
就不會(huì)繼續(xù)上傳了弦疮。為了在暫停完后可以繼續(xù)發(fā)送,需要在每次成功發(fā)送一個(gè)切片后將這個(gè)切片從 chunkList
數(shù)組里刪除 this.chunkList.splice(index, 1)
代碼匯總
<template>
<div id="app">
<!-- 上傳組件 -->
<el-upload action drag :auto-upload="false" :show-file-list="false" :on-change="handleChange">
<i class="el-icon-upload"></i>
<div class="el-upload__text">將文件拖到此處蜘醋,或<em>點(diǎn)擊上傳</em></div>
<div class="el-upload__tip" slot="tip">大小不超過 200M 的視頻</div>
</el-upload>
<!-- 進(jìn)度顯示 -->
<div class="progress-box">
<span>上傳進(jìn)度:{{ percent.toFixed() }}%</span>
<el-button type="primary" size="mini" @click="handleClickBtn">{{ upload | btnTextFilter}}</el-button>
</div>
<!-- 展示上傳成功的視頻 -->
<div v-if="videoUrl">
<video :src="videoUrl" controls />
</div>
</div>
</template>
<script>
import SparkMD5 from "spark-md5"
import axios from "axios"
export default {
name: 'App3',
filters: {
btnTextFilter(val) {
return val ? '暫停' : '繼續(xù)'
}
},
data() {
return {
percent: 0,
videoUrl: '',
upload: true,
percentCount: 0
}
},
methods: {
async handleChange(file) {
if (!file) return
this.percent = 0
this.videoUrl = ''
// 獲取文件并轉(zhuǎn)成 ArrayBuffer 對(duì)象
const fileObj = file.raw
let buffer
try {
buffer = await this.fileToBuffer(fileObj)
} catch (e) {
console.log(e)
}
// 將文件按固定大行踩(2M)進(jìn)行切片,注意此處同時(shí)聲明了多個(gè)常量
const chunkSize = 2097152,
chunkList = [], // 保存所有切片的數(shù)組
chunkListLength = Math.ceil(fileObj.size / chunkSize), // 計(jì)算總共多個(gè)切片
suffix = /\.([0-9A-z]+)$/.exec(fileObj.name)[1] // 文件后綴名
// 根據(jù)文件內(nèi)容生成 hash 值
const spark = new SparkMD5.ArrayBuffer()
spark.append(buffer)
const hash = spark.end()
// 生成切片压语,這里后端要求傳遞的參數(shù)為字節(jié)數(shù)據(jù)塊(chunk)和每個(gè)數(shù)據(jù)塊的文件名(fileName)
let curChunk = 0 // 切片時(shí)的初始位置
for (let i = 0; i < chunkListLength; i++) {
const item = {
chunk: fileObj.slice(curChunk, curChunk + chunkSize),
fileName: `${hash}_${i}.${suffix}` // 文件名規(guī)則按照 hash_1.jpg 命名
}
curChunk += chunkSize
chunkList.push(item)
}
this.chunkList = chunkList // sendRequest 要用到
this.hash = hash // sendRequest 要用到
this.sendRequest()
},
// 發(fā)送請(qǐng)求
sendRequest() {
const requestList = [] // 請(qǐng)求集合
this.chunkList.forEach((item, index) => {
const fn = () => {
const formData = new FormData()
formData.append('chunk', item.chunk)
formData.append('filename', item.fileName)
return axios({
url: '/single3',
method: 'post',
headers: { 'Content-Type': 'multipart/form-data' },
data: formData
}).then(res => {
if (res.data.code === 0) { // 成功
if (this.percentCount === 0) { // 避免上傳成功后會(huì)刪除切片改變 chunkList 的長(zhǎng)度影響到 percentCount 的值
this.percentCount = 100 / this.chunkList.length
}
this.percent += this.percentCount // 改變進(jìn)度
this.chunkList.splice(index, 1) // 一旦上傳成功就刪除這一個(gè) chunk啸罢,方便斷點(diǎn)續(xù)傳
}
})
}
requestList.push(fn)
})
let i = 0 // 記錄發(fā)送的請(qǐng)求個(gè)數(shù)
// 文件切片全部發(fā)送完畢后,需要請(qǐng)求 '/merge' 接口胎食,把文件的 hash 傳遞給服務(wù)器
const complete = () => {
axios({
url: '/merge',
method: 'get',
params: { hash: this.hash }
}).then(res => {
if (res.data.code === 0) { // 請(qǐng)求發(fā)送成功
this.videoUrl = res.data.path
}
})
}
const send = async () => {
if (!this.upload) return
if (i >= requestList.length) {
// 發(fā)送完畢
complete()
return
}
await requestList[i]()
i++
send()
}
send() // 發(fā)送請(qǐng)求
},
// 按下暫停按鈕
handleClickBtn() {
this.upload = !this.upload
// 如果不暫停則繼續(xù)上傳
if (this.upload) this.sendRequest()
},
// 將 File 對(duì)象轉(zhuǎn)為 ArrayBuffer
fileToBuffer(file) {
return new Promise((resolve, reject) => {
const fr = new FileReader()
fr.onload = e => {
resolve(e.target.result)
}
fr.readAsArrayBuffer(file)
fr.onerror = () => {
reject(new Error('轉(zhuǎn)換文件格式發(fā)生錯(cuò)誤'))
}
})
}
}
}
</script>
<style scoped>
.progress-box {
box-sizing: border-box;
width: 360px;
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 10px;
padding: 8px 10px;
background-color: #ecf5ff;
font-size: 14px;
border-radius: 4px;
}
</style>
復(fù)制代碼
效果如下圖: