首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用vue.js & element-ui的文件上传组件在上传到服务器前预览文件?

如何使用vue.js & element-ui的文件上传组件在上传到服务器前预览文件?
EN

Stack Overflow用户
提问于 2019-05-27 11:42:58
回答 2查看 1.8K关注 0票数 3

我正在使用vue.js & element-ui上传文件和预览文件。我想预览文件(.pdf/.docx/.jpg...)在上传到服务器之前。

代码语言:javascript
运行
复制
 <el-upload
          ref="uploadFile"
          :on-change="onUploadChange"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :file-list="fileList"
          :http-request="handleUpload"
          :data="extendData"
          :auto-upload="false"
          class="upload-demo"
          drag
          action="uploadUrl"
          multiple>
          <i class="el-icon-upload"/>
          <div class="el-upload__text">drag here, or <em>click to upload</em></div>
 </el-upload>

只有on-change功能才能获取文件内容,而on-preview功能只能获取元消息。如何获取上传到服务器之前的文件内容并进行预览?

EN

回答 2

Stack Overflow用户

发布于 2019-05-27 12:50:29

不是meta的问题,是文件的问题。因此,您需要在file上使用FileReader

代码语言:javascript
运行
复制
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)
}
票数 0
EN

Stack Overflow用户

发布于 2019-08-15 17:42:28

我还使用了Element-UI上传框,下面的代码允许用户将JSON文件导入到Vue中,并在单击文件名时在新窗口中预览其内容。在on-change期间,文件被读取并作为对象存储在data中,然后

Vue组件:

代码语言:javascript
运行
复制
<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>

脚本:

代码语言:javascript
运行
复制
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`);
    },
  },
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56319420

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档