美文网首页
Vue项目中文件上传兼容IE9

Vue项目中文件上传兼容IE9

作者: 假笑boys | 来源:发表于2022-10-18 10:29 被阅读0次

    因项目需要,客户指定使用IE9进行访问,所以,这里先讲一下,项目使用VUE编写,UI是ElementUI,但是Element的Upload组件是不兼容IE9的。因为IE9中无法使用FormData。

    传送门

    form表单实现文件上传的三种方式(适用于IE9)
    Vue在IE9中兼容上传 关于X-Frame-Options头
    IE浏览器加载不出来,按下F12就回复正常

    网上查阅资料基本两种解决方法:
    方法一:

    jQuery.form

    • 插件提供ajaxSubmit和ajaxForm两种表单提交方式,注意:不要对同一个表单同时使用两种方式。
    • ajaxSubmit是jQuery表单插件核心函数。非常灵活,因为它依赖于事件机制,只要有事件触发就能使用ajaxSubmit()提交表单,eg:超链接、图片、按钮的click事件。
    • ajaxSubmit(options)函数的一个封装,适用于表单提交的方式(注意,主体对象是<form>),会帮你管理表单的submit和提交元素([type=submit],[type=image])的click事件。在出发表单的submit事件时:阻止submit()事件的默认行为(同步提交的行为)并且调用$(this).ajaxSubmit(options)函数。
    $('#myForm').ajaxForm(function() {     
       $('#output1').html("提交成功!");      
    });    
             
    $('#myForm2').submit(function() {  
       $(this).ajaxSubmit(function() {     
          $('#output2').html("提交成功!");      
       });  
       return false; //阻止表单默认提交  
    }); 
    
    var options = {  
       target: '#output',          //把服务器返回的内容放入id为output的元素中      
       beforeSubmit: validate,  //提交前的回调函数  
       success: showResponse,      //提交后的回调函数  
       //url: url,                 //默认是form的action, 如果申明,则会覆盖  
       //type: type,               //默认是form的method(get or post),如果申明,则会覆盖  
       //dataType: null,           //html(默认), xml, script, json...接受服务端返回的类型  
       //clearForm: true,          //成功提交后,清除所有表单元素的值  
       //resetForm: true,          //成功提交后,重置所有表单元素的值  
       timeout: 3000               //限制请求的时间,当请求大于3秒后,跳出请求  
    }  
    function validate(formData, jqForm, options) { //在这里对表单进行验证,如果不符合规则,将返回false来阻止表单提交,直到符合规则为止  
       //方式一:利用formData参数  
       for (var i=0; i < formData.length; i++) {  
           if (!formData[i].value) {  
                alert('用户名,地址和自我介绍都不能为空!');  
                return false;  
            }  
        }   
      
       //方式二:利用jqForm对象  
       var form = jqForm[0]; //把表单转化为dom对象  
          if (!form.name.value || !form.address.value) {  
                alert('用户名和地址不能为空,自我介绍可以为空!');  
                return false;  
          }   
    }  
      
    function showResponse(responseText, statusText){  
       //dataType=xml  
       var name = $('name', responseXML).text();  
       var address = $('address', responseXML).text();  
       $("#xmlout").html(name + "  " + address);  
       //dataType=json  
       $("#jsonout").html(data.name + "  " + data.address);  
    }; 
    
    方法二: vue-upload-component

    安装

    npm install vue-upload-component --save

    使用

    • 设置this.$refs.upload.active = true,触发上传。
    • @input-filter是上传前的钩子函数,用于判断是否符合要求
    • @input-file是上传回调函数,每次上传的状态变化时 都会调用@input-file绑定的回调,形参是newFile, oldFile,通过新旧文件的对比来得到当前的状态
    • data:附加请求的参数
    • extensions:允许上传文件的后缀("jpg,gif,png,webp")
    • headers:自定义请求headers
    注意:文件上传之后的返回值 \color{#FF0000}{\rm\small{Content-Type}} 值不能是application/json 这会导致IE去解析返回结果,最终调用文件的保存或者打开,此处需要与后端协商将Content-Type改为\color{#FF0000}{\rm\small{text/plain }}

    代码如下

    <template>
    <ul>
        <li v-for="file in files">
          <span>{{file.name}}</span>
          <button type="button" @click.prevent="remove(file)">移除</button>
        </li>
      </ul>
    <file-upload 
      ref="upload"
      v-model="files" 
      post-action="/"
      @input-file="inputFile"
      @input-filter="inputFilter"
    >Upload file</file-upload> </template>
    <script>
    import 'vue-upload-component/dist/vue-upload-component.part.css'
    import FileUpload from 'vue-upload-component'
    export default {
      components: {
        FileUpload,
      },
      data() {
        return {
          files: []
        }
      }, methods: {
       remove(file) {
          this.$refs.upload.remove(file)//会触发inputFile中删除条件
        }
        /**
         * Has changed
         * @param  Object|undefined   newFile   只读
         * @param  Object|undefined   oldFile   只读
         * @return undefined
         */
        inputFile: function (newFile, oldFile) {
        if (newFile && !oldFile) {
            // 添加文件
          }
    
          if (newFile && oldFile) {
            // 更新文件
    
            // 开始上传
            if (newFile.active !== oldFile.active) {
              console.log('Start upload', newFile.active, newFile)
    
              // 限定最小字节
              if (newFile.size >= 0 && newFile.size < 100 * 1024) {
                newFile = this.$refs.upload.update(newFile, {error: 'size'})
              }
            }
    
            // 上传进度
            if (newFile.progress !== oldFile.progress) {
              console.log('progress', newFile.progress, newFile)
            }
    
            // 上传错误
            if (newFile.error !== oldFile.error) {
              console.log('error', newFile.error, newFile)
            }
    
            // 上传成功
            if (newFile.success !== oldFile.success) {
              console.log('success', newFile.success, newFile)
            }
          }
    
          if (!newFile && oldFile) {
            // 删除文件
    
            // 自动删除 服务器上的文件
            if (oldFile.success && oldFile.response.id) {
              // $.ajax({
              //   type: 'DELETE',
              //   url: '/file/delete?id=' + oldFile.response.id,
              // });
            }
          }
        // 自动上传
         if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
           if (!this.$refs.uploader.active) {
             this.$refs.uploader.active = true
           }
         }
    
        },
        /**
         * Pretreatment
         * @param  Object|undefined   newFile   读写
         * @param  Object|undefined   oldFile   只读
         * @param  Function           prevent   阻止回调
         * @return undefined
         */
        inputFilter: function (newFile, oldFile, prevent) {
          if (newFile && !oldFile) {
            // 过滤不是图片后缀的文件
            if (!/.(jpeg|jpe|jpg|gif|png|webp)$/i.test(newFile.name)) {
              return prevent()
            }
          }
    
          // 创建 blob 字段 用于图片预览
          newFile.blob = ''
          let URL = window.URL || window.webkitURL
          if (URL && URL.createObjectURL) {
            newFile.blob = URL.createObjectURL(newFile.file)
          }
    } }
    }
    </script>
    

    相关文章

      网友评论

          本文标题:Vue项目中文件上传兼容IE9

          本文链接:https://www.haomeiwen.com/subject/tddezrtx.html