vue上传pdf并预览
<td style="text-align: right;">体检报告:</td>
<td>
<input type="text" class="lng4" v-model="fileName">
</td>
<td>
<el-upload
class="upload-demo"
ref="upload"
action="/pdf/upload"
:show-file-list="false"
:before-upload="beforeUpload">
<el-button slot="trigger" size="mini" type="danger">选取文件</el-button>
</el-upload>
<el-button size="mini" @click="viewfile">预览</el-button>
<el-button size="mini" type="primary" @click="upLoadpdf()">上传</el-button>
</td>
data(){
return{
announcementType:'',
showDataImportDialog:true,
fileName:'',
announcementTypeOptions:[],
fileLevelOptions:[],
fileData:'',
}
}
methods:{
//上传PDF文件之前
beforeUpload(file){
console.log("文件", file);
this.file = file;
this.fileName = file.name;
// this.fileSize = file.size;
const extension = file.name.split('.').slice(-1) == 'pdf'
if (!extension) {
this.$message.warning('上传模板只能是pdf格式!')
return
}
let reader = new FileReader();
reader.readAsDataURL(file);
let that = this;
reader.onload = function() {
that.fileData = reader.result;
};
// return false; // 返回false不会自动上传
},
//预览文件
viewfile(){
console.log("viewFile",this.fileData);
// var win = window.open();
// var win =document.querySelector('.pdfClass');
// win.write(
// '<object data="' +
// this.fileData +
// '" type="application/pdf" width="100%" height="100%"><iframe src="' +
// this.fileData +
// '" scrolling="no" width="100%" height="100%" frameborder="0" ></iframe></object>'
// );
// win.document.write(
// '<body style="margin:0px;"><iframe src="' +
// this.fileData +
// '" scrolling="no" width="100%" height="100%" frameborder="0" ></iframe></body>'
// );
},
//上传文件按钮
upLoadpdf(){
if(this.fileName === ''){
this.$message.warning('请选择要上传的文件!');
return false
}
if(this.pdfForm.announcementType === ''){
this.$message.warning('请选择公告类型');
return false
}
if(this.pdfForm.fileLevel === ''){
this.$message.warning('请选择公告级别');
return false
}
//后端需要三个参数file、announcementType、fileLevel,用fileFormData包起来防止
// 出现 headers: 'multipart/form-data'等错误
// 若后端只需一个参数 添加
// let requestConfig = {
//headers: {
// 'Content-Type': 'multipart/form-data'
//},
//}
//this.axios.post('/market/upload',formData,requestConfig).then((res)=>
let fileFormData = new FormData();
fileFormData.append("file", this.file);
fileFormData.append('announcementType',this.pdfForm.announcementType)
fileFormData.append('fileLevel',this.pdfForm.fileLevel)
this.axios.post('/admin/uploadUserFile',fileFormData).then(res =>{
if (res.data.status===1){
this.$message({
message:res.data.msg,
type:'success',
duration: 3000,
});
this.showDataImportDialog=false
}else{
this.messageLabel = this.$message({
message:res.data.msg,
type:'error',
showClose:true,
duration:0,
});
}
})
},
},