原生js实现文件上传

function saveUser() {

            var file = document.getElementById("file").files[0];

            //原生ajax实现文件上传

            var formData = new FormData();

            if (file) {

                formData.append("file", file);

                console.log(file)

            }

            //得到xhr对象

            var xhr = null;

            if (XMLHttpRequest) {

                xhr = new XMLHttpRequest();

            } else {

                xhr = new ActiveXObject("Microsoft.XMLHTTP");

            }

            xhr.open("post", "http://www-test.mianyazhu.com/supplier/fileSupplier/file/upload/supplier", true);//设置提交方式,url,异步提交

//            xhr.setRequestHeader("Content-Type","multipart/form-data");

            xhr.onload = function () {

                var data = xhr.responseText;    //得到返回值

                console.log(data);

            }

            xhr.send(formData);

        }

你可能感兴趣的:(原生js实现文件上传)