上传图片 ajax input type="file" 兼容 ie chroem 火狐

上传图片,转载请注明出处!!!

兼容 ie chroem 火狐

html:

<div id="uploadForm">
    <input id="file" type="file"/>
    <button id="upload" type="button">upload</button>
</div>

jQuery Ajax:

html没有<form>标签,也没有enctype="multipart/form-data"属性

<script>
           $(document).ready(function(){
                   $("#upload").on("click", function(e) { //触发方法1:按钮点击事件
                      var file=$('#file')[0].files[0];
                      upLoadFile(file);
                 });
                
                $("#file").on("change", function(e) { //触发方法2:监听file的change事件
                    var file = e.target.files[0];
                    upLoadFile(file);
                });
           });

            function upLoadFile(file){
                var fd = new FormData();
                if (file.size < 4194304) { //判断文件大小  (Ps. ie9下获取图片size $("#file").context.fileSize)
                    fd.append("UserName", "Wt");
                    fd.append("Platform", 666); // 数字666被立即转换成字符串"666"
                    fd.append("file", file);
                    console.log(fd);
                    $.ajax({
                        url: "/User/UploadAvatar",
                        type: "POST",
                        data: fd,
                        contentType: false, //告诉jQuery不要去处理发送的数据(必需,不然报错)
                        processData: false, //告诉jQuery不要去设置Content-Type请求头(必需,不然报错)
                        success: function(result) {
                            //成功do
                        },
                        error: function(result) {
                            //报错do
                        }
                    });
                }
            }
        </script>

附:

 ajax错误 Uncaught TypeError: Illegal invocation (未捕获类型错误:非法调用)

这种错误可以参考:可能是应为 contentType: false,processData: false 没有加

检查jQuery的文档后发现,如果它不是一个字符串,jQuery的尝试将数据转换成一个字符串。因此,我们需要增加一个选项:processData:false,在这里告诉jQuery不要碰我的数据!另一种选择的contentType:false以防止jQuery来为你添加一个Content-Type头,否则字符串将被丢失和上传失败。

原文地址:https://www.cnblogs.com/wteng/p/5472811.html