• vue 文件上传


     

    学习参考地址:

    http://www.cnblogs.com/zhengweijie/p/6922808.html#3920491

    依赖js文件:

    http://files.cnblogs.com/files/zhengweijie/jquery.form.rar

    HTML 文本内容:

    <template>

      <div id="accident">

          <div class="wrapper">

            <i class="icon-pic"></i>相关照片

            <button type="button" @click="change_input()">上传照片</button>

            <form id="addTextForm" @change="setImg($event)">

            </form>

          </div>

          <div id="img-wrapper" @click="deleteImg($event)"></div>

          <P class="btn-wrapper">

              <mt-button type="primary" @click="submit()">提交</mt-button>

          </P>

      </div></template>

    Js脚本内容:

    <script>

        /**

        * file 域获取 本地图片 url

        */ 

        function getFileUrl(obj) {

          let url;

          url = window.URL.createObjectURL(obj.files.item(0));

          return url;

        }

    export default {

      name: 'accident',

      // 定义数据  data () {

        return {

          imgNum:4,    //上传的照片数量,可根据实际情况自定义        

        }

      },//定义事件   methods:{

          //根据点击上传按钮触发input      change_input(){

            let inputArr=$('#addTextForm input');

            let add_inputId='';     //需要被触发的input

            for(let i=0;i<inputArr.length;i++){

                // 根据inputvalue值判断是否已经选择文件

              if(!inputArr[i].value){          //如果没有选择,获得这个inputID      

                 add_inputId=inputArr[i].id;

                 break;

              }

            }

            if(add_inputId){                   //如果需要被触发的input ID存在,将对应的input触发

              return  $("#"+add_inputId).click();

            }else{

              alert("最多选择"+this.imgNum+"张图片")

            }

          },

          //input选择了图片的时候触发,将获得的src赋值到相对应的img      setImg(e){

            let target=e.target;

            $('#img_'+target.id).attr('src',getFileUrl(e.srcElement));

          },

          //点击图片删除该图片并清除相对的input      deleteImg(e){

            let target=e.target;

            let inputID='';       //需要清除valueinput

            if(target.nodeName=='IMG'){

              target.src='';

              inputID=target.id.replace('img_','');    //获得需要清除valueinput

              $('input#'+inputID).val("");

            }

          },

          //提交信息到后台      submit(){

                $("#addTextForm").ajaxSubmit({

                           url: this.$root.api+"/Index/staff_accident/add",      

                           type: "post",

                           data: {

                                    'total_price':this.price,

                                    'descript':this.descript,

                                },

                           success:  (data) => {

                                if(data.code==0){

                                  console.log(‘提交成功’);
                                   $("#addTextForm input").val('');

                                     $('div#img-wrapper img').attr('src','');

                               }else{

                                    alert('提交失败');

                                 }

                            }

                });  

            }

       },

      //页面加载后执行  mounted(){

        for(let i=0;i<this.imgNum;i++){

         //生成input框,默认为1

        let my_input = $('<input type="file" name="image" />');   //创建一个input

        my_input.attr('id',i);                           //为创建的input添加id

        $('#addTextForm').append(my_input);                     //将生成的input追加到指定的form

        //生成img,默认为1

        let my_img = $('<img src="">');

        my_img.attr('id', 'img_'+i);

        my_img.css({"max-width":"50%","max-height":"200px"});   //添加样式,由于vue的执行机制,页面加载的时候img标签还没有生成,直接写在style样式会不生效

        $('#img-wrapper').append(my_img);

        }

      },

    }</script>

    Vue项目使用quill-editor带样式编辑器(更改插入图片和视频)

    一、npm 安装 vue-quill-editor

    二、在main.js中引入

    import  VueQuillEditor from 'vue-quill-editor'

     

    Vue.use(VueQuillEditor)

     

    HTML部分:为编辑器绑定各个API事件,定义一个隐藏的input框,用于点击图片或者视频图标上传文件
    <template> <div> <!-- quill-editor插件标签 分别绑定各个事件--> <quill-editor v-model="content" ref="myQuillEditor" :options="editorOption" @blur="onEditorBlur($event)" @focus="onEditorFocus($event)" @change="onEditorChange($event)"> </quill-editor> <div class="limit">当前已输入 <span>{{nowLength}}</span> 个字符,您还可以输入 <span>{{SurplusLength}}</span> 个字符。</div> <!-- 文件上传input 将它隐藏--> <el-upload class="upload-demo" :action="qnLocation" :before-upload='beforeUpload' :data="uploadData" :on-success='upScuccess' ref="upload" style="display:none"> <el-button size="small" type="primary" id="imgInput" v-loading.fullscreen.lock="fullscreenLoading" element-loading-text="插入中,请稍候">点击上传</el-button> </el-upload> </el-table> </div> </template>

    CSS部分:

    .quill-editor {

      height: 745px;

     

      .ql-container {

        height: 680px;

      }

    }

     

    .limit {

      height: 30px;

      border: 1px solid #ccc;

      line-height: 30px;

      text-align: right;

     

      span {

        color: #ee2a7b;

      }

    }

     

    .ql-snow .ql-editor img {

      max- 480px;

    }

     

    .ql-editor .ql-video {

      max- 480px;

    }

     JS部分:

     

    import Vue from 'util/vueExt'

    import { Component } from 'vue-property-decorator'

    import * as Template from './editor.vue'

    import * as Quill from 'quill'    // 引入编辑器

    const STATICDOMAIN = '//ss.yidejia.com/'

    const STATVIDEO = '//flv.yidejia.com/'

     

    @Component({

      mixins: [Template]

    })

    export default class Editor extends Vue {

      content = ''    // 文章内容

      editorOption = {}    // 编辑器选项

      addRange: any = new Array()

      uploadData = {}

      photoUrl = ''         // 上传图片地址

      uploadType = ''    // 上传的文件类型(图片、视频)

      fullscreenLoading = false

     

      $refs: {

        myQuillEditor: any,

        imgInput: any

      }

     

      get nowLength() {

        return this.content.length

      }

     

      get SurplusLength() {   // 计算属性 获得当前输入字符长度

        let num = 10000 - Number(this.content.length)

        if (num > 0) {

          return num

        } else {

          return 0

        }

      }

     

      // 上传七牛的actiond地址  get qnLocation() {

        if (location.protocol === 'http:') {

          return 'http://up-z0.qiniu.com'

        }

        return 'https://up-z0.qbox.me'

      }

     

      // 图片上传前获得数据token数据  qnUpload(file) {

        this.fullscreenLoading = true

        const suffix = file.name.split('.')

        const ext = suffix.splice(suffix.length - 1, 1)[0]

        console.log(this.uploadType)

        if (this.uploadType === 'image') {  // 如果是点击插入图片

          return this.api.getQNToken().then(res => {

            this.uploadData = {

              key: `image/${suffix.join('.')}_${new Date().getTime()}.${ext}`,          token: res

            }

          })

        } else if (this.uploadType === 'video') {  // 如果是点击插入视频

          return this.api.getVideoQNToken().then(res => {

            this.uploadData = {

              key: `video/${suffix.join('.')}_${new Date().getTime()}.${ext}`,          token: res

            }

          })

        }

      }

     

      // 图片上传之前调取的函数  beforeUpload(file) {

        return this.qnUpload(file)

      }

     

      // 图片上传成功回调   插入到编辑器中  upScuccess(e, file, fileList) {

        this.fullscreenLoading = false

        let vm = this

        let url = ''

        if (this.uploadType === 'image') {    // 获得文件上传后的URL地址

          url = STATICDOMAIN + e.key

        } else if (this.uploadType === 'video') {

          url = STATVIDEO + e.key

        }

        if (url != null && url.length > 0) {  // 将文件上传后的URL地址插入到编辑器文本中

          let value = url

          vm.addRange = vm.$refs.myQuillEditor.quill.getSelection()

          value = value.indexOf('http') !== -1 ? value : 'http:' + value

          vm.$refs.myQuillEditor.quill.insertEmbed(vm.addRange !== null ? vm.addRange.index : 0, vm.uploadType, value, Quill.sources.USER)   // 调用编辑器的 insertEmbed 方法,插入URL

        } else {

          (<any>this).$message.error(`${vm.uploadType}插入失败`)

        }

        this.$refs['upload'].clearFiles()    // 插入成功后清除input的内容  }

     

      // 点击图片ICON触发事件  imgHandler(state) {

        this.addRange = this.$refs.myQuillEditor.quill.getSelection()

        if (state) {

          let fileInput = document.getElementById('imgInput')

          fileInput.click() // 加一个触发事件    }

        this.uploadType = 'image'

      }

     

      // 点击视频ICON触发事件  videoHandler(state) {

        this.addRange = this.$refs.myQuillEditor.quill.getSelection()

        if (state) {

          let fileInput = document.getElementById('imgInput')

          fileInput.click() // 加一个触发事件    }

        this.uploadType = 'video'

      }

     

      // 编辑器光标离开 将编辑器内容发射给父组件  onEditorBlur(editor) {

        this.$emit('getValue', this.content)

      }

     

      // 编辑器获得光标  onEditorFocus(editor) {

        editor.enable(true)   // 实现达到上限字符可删除  }

     

      // 编辑器文本发生变化  onEditorChange({ editor, html, text }) {

        let textLength = text.length

        if (textLength > 10000) {

          (<any>this).$message.error('最多输入10000个字符')

          editor.enable(false)

        }

        this.$emit('getValue', this.content)

      }

     

      // 清除编辑器内容  callMethod() {

        this.content = ''

      }

     

      // 页面加载后执行 为编辑器的图片图标和视频图标绑定点击事件  mounted() {

        // 为图片ICON绑定事件  getModule 为编辑器的内部属性

        this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('image', this.imgHandler)

        this.$refs.myQuillEditor.quill.getModule('toolbar').addHandler('video', this.videoHandler)  // 为视频ICON绑定事件  }

    }

  • 相关阅读:
    time,implicitly_wait,WebDriverWait三种等待方式
    iframe,window,alert切换
    pandas
    TestCase,Testsuit,TestLoder,TextTestRunner实现对测试用例全部执行或部分执行
    静态,类,实例,冒泡
    configparser读取
    ddt,data,unpack用法
    mybatis入门教程之搭建一个简单的mybatis项目并启动它
    修改hosts文件后不生效,该怎么办
    在JavaScript种遇到这样的错误如何解决XML 解析错误:格式不佳 位置:http:/... 行 27,列 32:
  • 原文地址:https://www.cnblogs.com/tianxujun/p/11377091.html
Copyright © 2020-2023  润新知