分片及七牛雲上傳封裝
項目裏面用到七牛雲,有分片和簡單上傳vue
在此作下簡單的記錄,分享ios
下面是分片上傳封裝json
process.env.MAX_FILESIZE 是我寫在config裏面分片的大小 如1024102410 10MB分片axios
項目是vue框架,請求是axios。網絡
上傳的進度在onUploadProgress中獲取app
/** * 封裝upload方法 * @param url 上傳路徑 * @param json 包含file對象 * @returns {Promise} */ export function upload(url,json) { return new Promise((resolve,reject) => { let size = parseInt(Number(json.file.size)/Number(process.env.MAX_FILESIZE) +1); let y = 0; let fun = function(){ let formData = new FormData(); let file = json.file.slice(y*process.env.MAX_FILESIZE,(y+1)*process.env.MAX_FILESIZE); formData.append('chunk', y); formData.append('file_name', json.file.name); formData.append('count', size); formData.append('type', json.type); formData.append('file', file); axios.post(url,formData,{ headers: { 'Content-Type': 'multipart/form-data' },timeout:10000000, onUploadProgress: progressEvent => { //progressEvent.loaded 爲上傳進度 }, }).then(response => { if(response.data.code === 200){ if(y+1<size){ y++; fun() }else{ y=0; resolve(response.data.data); } }else{ Vue.prototype.$message.error(response.data.msg) } }) .catch(err => { reject(err); let message = '請求失敗!請檢查網絡'; if(err.response)message=err.response.data.message; Vue.prototype.$$msgbox({ title:'錯誤!', message:message, type:'error', }) }) }; fun() } }) }
下面是七牛雲上傳的封裝框架
/** * 封裝upload方法 * @param json json中包含fail * @returns {Promise} */ export function uploadQiniu(json) { return new Promise((resolve,reject) => { axios.get('獲取七牛權限的後臺接口地址,主要獲取七牛token',{ params:{ file_name:json.file.name } }).then(resData =>{ let putExtra = { fname: json.file.name, mimeType:json.mimeType || null }; let congif = {}; let observable = qiniu.upload(json.file,resData .data.data.new_name,resData .data.data.token,putExtra,congif); let observer = { next(res){ let progress = Number(res.total.percent.toFixed(0)); // 此處獲得上傳進度百分比 可加後續操做 }, error(err){ reject(err); let message = '請求失敗!請檢查網絡'; if(err.response)message=err.response.data.message; Vue.prototype.$alert({ title:'錯誤!', message:message, type:'error', }) }, complete(res){ res.url = res.key; res.name = json.file.name; resolve(res); } }; let subscription = observable.subscribe(observer) } ); })
}post