後端小夥伴寫好了接口,vue寫個方法獲取,建議使用Promisevue
/// vue寫獲取token方法
async getPicToken({ commit }) {
try {
const { result } = await request({
url: getTokenURL,
commit,
})
// 這裏爲了後去控制流程 => return Promise
return Promise.resolve(result)
} catch (e) {
$message(e.message)
}
},
複製代碼
const file = document.getElementById('file')
const formData = new FormData()
const time = new Date().getTime()
const token = await this.getPicToken()
formData.append('file', file)
formData.append('key', `video${time}`)
formData.append('file', file)
formData.append('token', token)
request({
url: 'http://upload.qiniu.com',
method: 'POST',
data: formData,
}).then(res => {
console.log(res)
})
複製代碼
咱們獲取了token打通了上傳 可是,上傳後文件讀取出問題,咱們換個思路,直接用elementui upload組件java
elementui文檔數據庫
<el-upload
ref="upload"
action="http://upload.qiniup.com"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:auto-upload="true"
:limit="1"
:data="form"
>
<el-button slot="trigger" size="small" type="primary">選取文件</el-button>
</el-upload>
複製代碼
上傳url我這裏是
http://upload.qiniup.com
不一樣的用不一樣的url 文檔地址後端
async beforeAvatarUpload(file) {
const fileType = file.type
const current = new Date().getTime()
const key = `video_${current}` // key爲上傳後文件名 必填
const isLt20M = file.size / 1024 / 1024 < 20 // 算出文件大小
this.fileSize = file.size // 存儲文件大小
if (!isLt20M) { // 這裏咱們限制文件大小爲20M
this.$message.error('最大隻能上傳20M!')
this.$ref.upload.abort()
return isLt20M
}
if (fileType !== 'video/mp4') { // 限制文件類型
this.$ref.upload.abort()
this.$message.error('只能上傳MP4格式視頻!')
return false
}
try {
const token = await this.getPicToken()
this.form = {
key,
token,
}
return true
} catch (error) {
return error
}
},
複製代碼
before-upload 若是返回false或者 返回promise reject會終止,可是實測仍是會調用七牛運上傳,不過沒有token和數據也能接受promise
這裏一直出現一個問題:上傳到七牛雲一直報400錯誤bash
懷疑是異步搞得鬼服務器
auto-upload:false
submitUpload() {
this.$refs.upload.submit()
},
複製代碼
仍是出問題 懷疑是token慢了 在頁面一加載的時候獲取token 仍是不對app
查了半天終於發現 必定要在data寫form //this is !importantless
上傳若是不符合要求 還會顯示上傳進度
解決辦法:在beforeAvatarUpload return前 this.$ref.upload.abort() 能夠中斷上傳
文檔說clearFiles不能用 實測可用 爲了穩定 仍是使用abort
萬惡的產品還要加圖片上傳 並且加只能上傳一張的限制 文檔中說是使用limit 咱們在組件裏使用limit=1 發現仍是有上傳的按鈕
這裏咱們經過css的辦法解決
<el-upload
:class="{hide:!isShowUpload}"
ref="upload"
action="http://upload.qiniup.com"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:auto-upload="true"
:limit="1"
:accept="'image/*'"
:data="form"
list-type="picture-card"
>
<i class="el-icon-plus"></i>
<!-- <el-button v-show="isShowUpload" slot="trigger" size="small" type="primary"></el-button> -->
<!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上傳到服務器</el-button> -->
</el-upload>
<style lang='less'>
.hide .el-upload--picture-card {
display: none;
}
</style>
複製代碼
這裏咱們操做不到按鈕 可是咱們發現它有el-upload--picture-card這個class
因此在el-upload 加個hide class :class="{hide:!isShowUpload}" 能夠解決
注:在vue有個小問題,通常咱們在style裏會寫scoped 上面寫法會不生效,須要去除scoped