我正在使用vue.js和element-ui来上传文件和预览文件。我想先预览文件(.pdf / .docx / .jpg ...),然后再上传到服务器。
<head>
<script src="sample_code.js"></script>
</head>
只有on-change功能可以获取文件的内容,而on-preview功能只能获取元消息。如何获取文件内容并预览文件内容,然后再上传到服务器?
答案 0 :(得分:0)
不是meta
,而是文件。因此,您需要在FileReader
上使用file
:
handlePreview(file) {
const reader = new FileReader()
reader.onload = e => console.log(e.target.result) // here is the result you can work with.
reader.readAsText(file)
}
答案 1 :(得分:0)
我也在使用Element-UI上传框,以下代码允许用户将JSON文件导入Vue,并在单击文件名时在新窗口中预览其内容。在data
期间读取文件并将其作为对象存储在on-change
中,然后
Vue组件:
<el-upload class="upload-box" drag action="" :auto-upload="false" :on-change="handleImport" :on-preview="handlePreview" :limit="1" :on-exceed="handleExceed">
<i class="el-icon-upload"></i>
<div class="el-upload__text">Drop file here or <em>click to upload</em></div>
<div class="el-upload__tip" slot="tip">Single JSON file with size less than 500kb</div>
</el-upload>
脚本:
export default {
data() {
return {
uploadFile: null,
fileContent: null,
}
},
methods: {
handleImport(file) {
this.uploadFile = file
let reader = new FileReader()
reader.readAsText(this.uploadFile.raw)
reader.onload = async (e) => {
try {
this.fileContent = JSON.parse(e.target.result)
} catch (err) {
console.log(`Load JSON file error: ${err.message}`)
}
}
},
handlePreview() {
let myWindow = window.open();
myWindow.document.write(JSON.stringify(this.fileContent));
myWindow.document.close();
},
handleExceed(files, fileList) {
this.$message.warning(`The limit is 1, you selected ${files.length + fileList.length} totally, please first remove the unwanted file`);
},
},
}