通过Ajax方式上传文件(input file),使用FormData进行Ajax请求

屠昌胤
2023-12-01
< div >
    < input  type="file" name="FileUpload" id="FileUpload">
    < a  class="layui-btn layui-btn-mini" id="btn_uploadimg">上传图片</ a >
</ div >
<script type= "text/jscript" >
 
        $( function  () {
            $( "#btn_uploadimg" ).click( function  () {
                var  fileObj = document.getElementById( "FileUpload" ).files[0];  // js 获取文件对象
                if  ( typeof  (fileObj) ==  "undefined"  || fileObj.size <= 0) {
                    alert( "请选择图片" );
                    return ;
                }
                var  formFile =  new  FormData();
                formFile.append( "action" "UploadVMKImagePath" );  
                formFile.append( "file" , fileObj);  //加入文件对象
 
                //第一种  XMLHttpRequest 对象
                //var xhr = new XMLHttpRequest();
                //xhr.open("post", "/Admin/Ajax/VMKHandler.ashx", true);
                //xhr.onload = function () {
                //    alert("上传完成!");
                //};
                //xhr.send(formFile);
 
                //第二种 ajax 提交
 
                var  data = formFile;
                $.ajax({
                    url:  "/Admin/Ajax/VMKHandler.ashx" ,
                    data: data,
                    type:  "Post" ,
                    dataType:  "json" ,
                    cache:  false , //上传文件无需缓存
                    processData:  false , //用于对data参数进行序列化处理 这里必须false
                    contentType:  false //必须
                    success:  function  (result) {
                        alert( "上传完成!" );
                    },
                })
            })
        })
 
    </script>
补充 IE8 不支持.files 写法
 类似资料: