FormData append not working

后端 未结 2 1920
情歌与酒
情歌与酒 2020-12-29 01:43

I wrote this to upload an image to my local Apache webserver using input element in HTML. The file is logged as not empty, but why is the for

相关标签:
2条回答
  • 2020-12-29 01:54

    When logging a formData object with just console.log(formData) it always returns empty, as you can't log formData.

    If you just have to log it before sending it, you can use entries() to get the entries in the formData object

    $('#upload-image').change(function(e) {
        var file = e.target.files[0];
        var imageType = /image.*/;
    
        if (!file.type.match(imageType)) return;
    
        var form_data = new FormData();
        form_data.append('file', file);
    
        for (var key of form_data.entries()) {
            console.log(key[0] + ', ' + key[1]);
        }
    
        $.ajax({
            url: 'http://localhost/upload.php',
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            type: 'POST',
            success: function(response) {
                console.log(response);
            },
            error: function(error) {
                console.log(error);
            }
        });
    
    });
    
    0 讨论(0)
  • 2020-12-29 02:12

    I've noticed myself that the contentType: false will only work on jQuery 1.7.0 and above. So make sure that you're using the right jQuery version.

    0 讨论(0)
提交回复
热议问题