通过fromdata实现上传文件

版权声明:本文为QQ帝国原创博客,转载请附上链接,谢谢。 https://blog.csdn.net/QQ_Empire/article/details/88084215

其实呢,文件上传的插件很多,可是现在做的东西要求尽量少用插件,所以就自己写了一下。


例子1:a.html文件

<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/html">  
<head>  
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<html>  
<head>  
<title></title>  

</head>  
  
<body>  
<form enctype="multipart/form-data" id="uploadImg">
    上传文件:  
    <input name="file" type="file" id="file"> 
</form>
</body>  
</html>
<script src="jquery.js"></script>
<script>
    $(function(){
        $('input[type="file"]').on('change', function(){
            var file = this.files[0];
            var formData = new FormData($('#uploadImg')[0]);
            formData.append('file', file);
            console.log(formData.get('file'))
            $.ajax({
                url: 'b.php',
                type: 'POST',
                cache: false,
                data: formData,
                //dataType: 'json',
                //async: false,
                processData: false,
                contentType: false,
            }).done(function(res) {
                console.log(res)
            }).fail(function(res) {
                console.log(res)
            });
        });
    })
</script>

例子2:vue中写法

<form id="form" enctype="multipart/form-data">

      <input id="folder" type='file' name="file" webkitdirectory>
      <input id="submit" type="button" value="提交" @click="submit"> 

</form> 
    submit(){
            $.ajax({
                url: this.portC+"uploadDirectory",
                type: 'POST',
                cache: false,
                data: new FormData($('#form')[0]),
                processData: false,
                contentType: false
            }).done((res)=> {

                console.log(res)
                
                               
            })
    }   

猜你喜欢

转载自blog.csdn.net/QQ_Empire/article/details/88084215