美文网首页
通过FormData实现上传文件

通过FormData实现上传文件

作者: duans_ | 来源:发表于2018-09-05 14:48 被阅读17次

    html代码

    index.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="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.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: 'upload.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>
    

    后端代码(以php为例)

    upload.php

    <?php
        //print_r($_FILES);    
        $uptypes=array(  
            'image/jpg',  
            'image/jpeg',  
            'image/png',  
            'image/pjpeg',  
            'image/gif',  
            'image/bmp',  
            'image/x-png'  
        );
    
        $max_file_size=200000000;     //上传文件大小限制, 单位BYTE
        
        $file=$_FILES["file"];
        $fileName=$file["name"];
        $filetype = $file["type"];
        $filesize = $file["size"];
        
        if(!in_array($filetype, $uptypes)){            // 文件类型判断
            echo "文件类型不符!";
            exit;
        }
        if($filesize > $max_file_size){                // 文件大小判断
            echo "文件太大!";
            exit;    
        }
        if (!is_dir("image/")) {                    //创建路径
            mkdir("image/");
        }
        $url = "image/";
        //当文件存在
        if (file_exists($url.$fileName)) {
            //echo $fileName." already exists.";
            echo $url.$fileName;
        }else{//当文件不存在
            $url=$url.$fileName;
            move_uploaded_file($_FILES["file"]["tmp_name"],$url);
            echo $url;
        }
    ?>
    

    注意事项

    • 在PHP中通过print_r($_FILES)打印时,有时候formData里面的参数type会为空,而在前端打印的formData.get('file')里是有type的值的,原因是PHP导入文件(我是导的图片)有大小限制
      解决方法:在php.ini中,搜索upload_max_filesize(默认为2M),修改这个值,重启服务器即可。

    • 在通过ajax进行数据请求时,console.log(formData)对象为空,而且在append后还是为空,是因为属性不是直接挂载在你这个FormData,可以通过get方法进行获取。

    • 在一般情况下使用ajax请求,processData(默认为true)不需要设置,但是当使用fromdata上传文件时,发送的对象不需要转化为对象,所以必须设置为false。

    相关文章

      网友评论

          本文标题:通过FormData实现上传文件

          本文链接:https://www.haomeiwen.com/subject/zvyawftx.html