1、安装
cnpm i vue-pdf --save
2、使用
<el-form-item label="上传文件" >
<el-upload
class="avatar-uploader"
action="customize"
ref="upLoad"
:accept="'.pdf'"
:http-request="pdfUpLoad"
:show-file-list="true"
:file-list="fileArr"
:on-exceed="handleExceed"
:on-remove="handleRemove"
:on-preview="showPdf"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload"
:limit="1"
>
<i class="el-icon-upload avatar-uploader-icon"></i>
<div class="el-upload__tip" slot="tip">
支持pdf文件,且不超过10M
</div>
</el-upload>
</el-form-item>
<div class="pdf_wrapper" v-if="pdfUrl" v-loading="loading">
<pdf
v-for="i in pdfTotal"
:key="i"
:src="pdfUrl"
:page="i"
@page-loaded="handlePdfLoaded"
ref="pdf"
>
</pdf>
</div>
import pdf from "vue-pdf";
components: { pdf },
data(){
return {
pdfUrl: "",
pdfTotal: 1,
}
},
methods:{
// -----------------------PDF上传
async pdfUpLoad(params) {
// 通过 FormData 对象上传文件
const _file = params.file;
var formData = new FormData();
formData.append("files", _file);
let res = await uploadPdf(formData);
console.log('上传完成',res);
if (res.code !== 1) return this.$message.error(res.message);
this.ruleForm.filePath = res.data;
this.fileArr.push(...res.data);
// this.fileArr.push({
// id:Math.random(),
// url:res.data[0]
// });
this.$message.success("文件上传成功!");
},
showPdf(file) {
this.loading = true;
let url=''
if(this.actionType==0){
url = window.URL.createObjectURL(file.raw); //将文件转化成url
}else{
url = file.url; //将文件转化成url
}
console.log(url, "pdfwenjain ");
this.pdfUrl = url;
let loadingTask = pdf.createLoadingTask(url);
loadingTask.promise
.then((pdf) => {
this.pdfTotal = pdf.numPages;
})
.catch((err) => {
console.error("pdf 加载失败", err);
});
},
handleAvatarSuccess(res, file, fileList) {
console.log(res, file, fileList,'上传充公')
this.fileName = file.name
},
handleRemove(file,fileList){
console.log(file,fileList,'删除')
this.fileArr=fileList;
this.ruleForm.filePath=[]
this.fileName = ''
},
handleExceed(files, fileList) {
this.$message.warning(
`当前限制选择1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${fileList.length} 个文件`
);
},
beforeAvatarUpload(file) {
const fileSuffix = file.name.substring(file.name.lastIndexOf(".") + 1);
const whiteList = ["pdf"];
if (whiteList.indexOf(fileSuffix) === -1) {
this.$message.error("上传文件只能是 pdf");
return false;
}
},
// 加载
handlePdfLoaded(e) {
if (e === this.pdfTotal) {
this.$nextTick(() => {
setTimeout(() => {
this.loading = false;
}, 500);
});
}
},
}