HTML
<el-upload
drag
:limit="1"
:auto-upload="false"
accept=".doc,.docx"
:action="UploadUrl()"
:before-upload="beforeUploadFile"
:on-change="fileChange"
:on-exceed="exceedFile"
:on-success="handleSuccess"
:on-error="handleError"
:file-list="fileList"
:on-remove="removeFile"
:on-preview="handlePreview"
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip" style="color: red">
只能上传word文件,且不超过10M
</div>
</el-upload>
<br />
<el-button size="mini" type="primary" @click="uploadFile"
>立即上传</el-button
>
JS
UploadUrl() {
// 因为action参数是必填项,我们使用二次确认进行文件上传时,直接填上传文件的url会因为没有参数导致api报404,
所以这里将action设置为一个返回为空的方法就行,避免抛错
return "";
},
// 文件状态改变时的钩子
fileChange(file, fileList) {
console.log(file.raw);
this.fileList.push(file.raw);
console.log(this.fileList);
},
// 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传
beforeUploadFile(file) {
console.log("before upload");
console.log(file);
let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
let size = file.size / 1024 / 1024;
if (extension !== "doc") {
this.$message.warning("只能上传后缀是.doc");
}
if (size > 10) {
this.$message.warning("文件大小不得超过10M");
}
},
// 下载
handlePreview(file) {
console.log("下载", file);
var link = document.createElement("a");
link.download = file.name;
link.href = file.url[0].attUrl;
link.click();
window.URL.revokeObjectURL(link.href);
},
// 文件上传
uploadFile() {
if (this.fileList.length === 0) {
this.$message.warning("请上传文件");
} else {
console.log(111, this.fileList.length);
let form = new FormData();
form.append("file", this.fileList[0]);
form.append("uid", this.fileList[0].uid);
uploadReportFile(form).then((res) => {
if (res.statusCode == 200) {
// console.log("文件上传", res);
this.$message.success("文件上传成功");
this.fileSuccList.push(res.data); //上传成功之后的文件信息
}
});
}
},