Vue+ElementUI实现文件的下载与上传

    当需要批量导入的时候,一般会提供下载示例文件的功能。实现下载功能直接使用<a>标签即可。

<a class='download' :href='downloadhttp' download=""  title="下载">下载</a>

downloadhttp为文件下载的路径,download属性是为了避免浏览器直接执行打开而不下载。路径是下载文件很重要的组成部分,一般为了方便维护都会将文件放在服务器,路径需要在apiconfig.js文件中判断是测试端还是服务器端,主要思路是将两端设置不同的baseUrl,在此不再赘述。downloadhttp = baseUrl + 路径相同部分。在Linux服务器上最好将文件名设置为英文,中文在解码时可能会出现偏差,导致文件寻找失败。

   文件的上传主要使用element中的el-upload。

<el-upload
  class="upload-demo"
  action="https://jsonplaceholder.typicode.com/posts/"
  :on-preview="handlePreview"
  :on-remove="handleRemove"
  :before-remove="beforeRemove"
  multiple
  :limit="3"
  :on-exceed="handleExceed"
  :file-list="fileList">
  <el-button size="small" type="primary">点击上传</el-button>
  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
<script>
  export default {
    data() {
      return {
        fileList: [{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]
      };
    },
    methods: {
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${ file.name }?`);
      }
    }
  }
</script>

其中action是必须的参数,用来写传输的接口地址。用的比较多的是on-success,这个钩子为上传成功时的回调,当传输完成后即可调用。无论后台接口返回何值,只要成功上传,就会调用该函数。但是在实际应用中,由于Excel填写的格式不正确等问题,会导致后台解析失败,返回success = 0.这时我们需要使用该方法来进行后续的操作。

<el-upload
  class="upload-demo"
  action=""
  :on-success='handlesuccess'
  multiple
  :limit="3"
  :on-exceed="handleExceed"
  :file-list="fileList">
  <el-button size="small" type="primary">点击上传</el-button>
</el-upload>
<script>
  export default {
    data() {
      return {
        fileList: []//此数组中存入所有提交的文档信息
      };
    },
    methods: {
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 3 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
      },
     handlesuccess(response, file, fileList){
    //response即为后台返回的全部内容
     if(response.success === 1){
       console.log('解析成功')
     }else{
        console.log('解析失败')
       }
     }
    }
  }
</script>

其次使用频率较高的为clearFiles方法,用来清除已选中的所有文档信息。上传时在dialog中进行,当关闭当前dialog,再次打开时需要清空上一次的数据,如果是表格表单类型,可直接将其绑定的数组对象清空,若是文件类型,则需要clearFiles方法来进行清除

猜你喜欢

转载自www.cnblogs.com/tomatoto/p/9594638.html