一个简单的文件预览案例(图片和pdf)

80 阅读1分钟
话不多说,直接看代码
// 预览图片、pdf
preview(_, row) {
	const type = row.name.split('.')[1]; // 文件类型
	if (type === 'png' || type === 'jpg' || type === 'jpeg' || type === 'pdf') {
		axios({
			url: `/download`,
			method: 'GET',
			params: {
				fileid: row.fileid // 文件id
			},
			responseType: 'blob'
		}).then(res => {
			if (type === 'pdf') {
				const binaryData = [];
				binaryData.push(res.data);       
				this.pdfUrl = window.URL.createObjectURL(new Blob(binaryData, {type: 'application/pdf'}));
				window.open(this.pdfUrl);
				
			} else {
				const url = URL.createObjectURL(res.data);
				const newWindow = window.open();
				newWindow.document.write(`
                                    <html>
                                      <head>
                                        <title>Image Preview</title>
			                    </head>
				            <body>
                                        <img src="${url}" style="max-width:100%; max-height:100%;" />
				            </body>
				           </html>`);

				newWindow.document.close();
				setTimeout(() => {
					URL.revokeObjectURL(url);
				}, 1000);
			}
		});
	} else {
		return this.$message({
			type: 'error',
			message: '不支持此文件格式预览'
		});
	}
},