Commit 50eb3725 authored by liujiangnan's avatar liujiangnan

debug

parent 40ce629c
......@@ -8,7 +8,6 @@
<link href="./index.css" rel="stylesheet" >
<script type="text/javascript" src="../lib/js/jquery-1.12.3.min.js"></script>
<script type="text/javascript" src="../lib/js/axios.min.js"></script>
<script type="text/javascript" src="../lib/common.js"></script>
<script type="text/javascript" src="../lib/vue.min.js"></script>
......
......@@ -27,7 +27,7 @@ new Vue({
uploadCover: window.courseware.uploadData(),
uploading: false,
uploadProgress: 0,
cancelTokenSource: null,
xhr: null,
}
},
methods: {
......@@ -35,40 +35,51 @@ new Vue({
this.uploading = true;
this.uploadProgress = 0;
// 创建 FormData
const formData = new FormData();
formData.append('file', options.file);
// 创建取消令牌
this.cancelTokenSource = axios.CancelToken.source();
// 创建 XMLHttpRequest
const xhr = new XMLHttpRequest();
// 发起上传请求
axios.post(this.uploadUrl, formData, {
cancelToken: this.cancelTokenSource.token,
withCredentials: true,
onUploadProgress: (progressEvent) => {
this.uploadProgress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
},
headers: {
'Content-Type': 'multipart/form-data'
// 保存 xhr 实例用于取消上传
this.xhr = xhr;
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) {
this.uploadProgress = Math.round((event.loaded * 100) / event.total);
}
}).then(response => {
this.handleCoverSuccess(response.data, options.file);
this.uploading = false;
this.cancelTokenSource = null;
}).catch(error => {
if (axios.isCancel(error)) {
console.log('上传已取消');
};
xhr.onload = () => {
if (xhr.status === 200) {
try {
const response = JSON.parse(xhr.responseText);
this.handleCoverSuccess(response, options.file);
} catch (e) {
this.handleCoverError(new Error('解析响应失败'));
}
} else {
this.handleCoverError(error);
this.handleCoverError(new Error('上传失败'));
}
this.uploading = false;
this.cancelTokenSource = null;
});
this.xhr = null;
};
xhr.onerror = () => {
this.handleCoverError(new Error('上传失败'));
this.uploading = false;
this.xhr = null;
};
xhr.open('POST', this.uploadUrl, true);
xhr.send(formData);
},
cancelUpload() {
if (this.cancelTokenSource) {
this.cancelTokenSource.cancel('用户取消上传');
if (this.xhr) {
this.xhr.abort();
this.xhr = null;
this.uploading = false;
this.uploadProgress = 0;
}
},
handleCoverSuccess(response, file, fileList) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment