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">  
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

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

b.php file:


    $max_file_size=200000000;     //Upload file size limit, Company BYTE
    $filetype = $file["type"];
    $filesize = $file["size"];
    if(!in_array($filetype, $uptypes)){            // Document type judgment
        echo "File type mismatch!";
    if($filesize > $max_file_size){                // File size judgment
        echo "File too large!";
    if (!is_dir("image/")) {                    //Create path
    $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
        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