使用fromData进行文件上传

319 阅读1分钟

前言:前段时间使用formdata进行文件上传时发现了些问题,就是headers始终为text,后台经过查证,需设置contentType为false

<input type="file" id="btn">
<button id="upload">上传</button>

<script>
    var file="";
    document.getElementById('cgfile').onchange=function(e){
        file = this.files[0];
        //预览
        var fileSrc=getObjectURL(file);
        var img = document.createElement('img');
        img.setAttribute('src',fileSrc);
        img.style.width='100px';
        img.style.height='100px';
        document.body.innerHTML = img.outerHTML;
    };
    document.getElementById('upload').onclick=function(){
        var formData = new FormData();
        formData.append('Content-Type',false);//文件上传时需设置
        formData.append('file',file);
        
        /*
        *如果使用$.ajax()上边可不用设置Content-Type.
        */
        //借用jquery
        $.ajax({
            type:'post',
            data:formData,
            processData:false,//不对参数进序列化处理
            contentType: false,//不设置请求头
            url:'http://192.168.1.1/upload.do',
            success:function(res){
                console.log(res);
            }
        })
    };
    //通过file对象获取url
    function getObjectURL(file) {
        var url = null ;
        if (window.createObjectURL!=undefined) { // basic
            url = window.createObjectURL(file);
        } else if (window.URL!=undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file);
        } else if (window.webkitURL!=undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file);
        };
        return url ;
    };
</script>