Upload files through fromdata

Keywords: Javascript PHP JQuery JSON Attribute

In fact, there are many plug-ins for file upload, but what we do now requires to use as few plug-ins as possible, so I wrote it myself.

I've also written about file processing with node before. This time, I'll try it in php.

a.html file

<!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">
    //Upload file:  
    <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>  

b.php file:

<?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;     //Upload file size limit, Company BYTE
    
    $file=$_FILES["file"];
    $fileName=$file["name"];
    $filetype = $file["type"];
    $filesize = $file["size"];
    
    if(!in_array($filetype, $uptypes)){            // Document type judgment
        echo "File type mismatch!";
        exit;
    }
    if($filesize > $max_file_size){                // File size judgment
        echo "File too large!";
        exit;    
    }
    
    if (!is_dir("image/")) {                    //Create path
        mkdir("image/");
    }
    $url = "image/";
    //When a file exists
    if (file_exists($url.$fileName)) {
        //echo $fileName." already exists.";
        echo $url.$fileName;
    }else{//When the file does not exist
        $url=$url.$fileName;
        move_uploaded_file($_FILES["file"]["tmp_name"],$url);
        echo $url;
    }
?>

There are also several problems in this process

1. When printing through print_r($_FILES) in PHP, sometimes the parameter type in formData will be empty, but there is a value of type in formData.get('file ') printed on the front end, because the PHP import file (I am the imported image) has a size limit

Solution: in php.ini, search for upload_max_filesize (2M by default), modify the value and restart the server.

2: When making a data request through ajax, the console.log(formData) object is empty, and it is still empty after append, because the attribute is not directly attached to your FormData, which can be obtained by get method.

Reference: https://segmentfault.com/q/101000001087308

3: In general, when using ajax requests, processData (true by default) does not need to be set, but when using fromdata to upload files, the sent objects do not need to be converted to objects, so it must be set to true.

Posted by asd on Tue, 05 May 2020 06:05:32 -0700