提交的PHP输入类型文件字段,文件不是

时间:2015-07-01 22:54:37

标签: php jquery forms file-upload

我有以下表格。

<form action="picture.php" method="POST" class="pic_form">
<span class="picture_box">
<input type="file" accept="image/*" name="pic_upload" class="picture_upload_input" />
<p class="upload_info">Only file types of the extensions gif, jpg, png and svg are allowed. The maximum file size is 15mb. If your file is larger than 15mb, it will not upload.</p>
</span>
<input type="hidden" name="uid" value="<?php echo $_SESSION['userid']; ?>" />
<input type="button" name="upload_button" value="Upload" class="upload_button" />
</form>

我使用jQuery验证文件是否已设置以及它的类型和大小是否正确。当我提交此表单(使用jQuery)时,该字段已发布

$_POST['pic_upload']

返回true。

但是,文件本身并未发布

$_FILES['custom_pic_upload']

返回false和

var_dump($_FILES['custom_pic_upload']);

返回null。

如何自行上传文件?

1 个答案:

答案 0 :(得分:1)

您的表单需要属性enctypehttps://developer.mozilla.org/en-US/docs/Web/HTML/Element/form

  

multipart / form-data:用于type属性设置为“file”的元素的值。

<form action="picture.php" method="POST" class="pic_form" enctype="multipart/form-data">
<span class="picture_box">
<input type="file" accept="image/*" name="pic_upload" class="picture_upload_input" />
<p class="upload_info">Only file types of the extensions gif, jpg, png and svg are allowed. The maximum file size is 15mb. If your file is larger than 15mb, it will not upload.</p>
</span>
<input type="hidden" name="uid" value="<?php echo $_SESSION['userid']; ?>" />
<input type="submit" name="upload_button" value="Upload" class="upload_button" />
</form>
<script type='text/javascript'> 
$('.upload_button').click(function(){ 
    var upload_ver_val = $('.picture_upload_input').val(); 
    if (upload_ver_val == '') { 
        alert("Please upload an image!");
        return false;
    } else {
        var ext = $('.picture_upload_input').val().split('.').pop().toLowerCase(); 
        if($.inArray(ext, ['gif','png','jpg','jpeg','svg']) == -1) {
            alert('Only file types of the extensions; gif, jpg, png and svg are allowed!');
            return false;
        } else { 
            $('.prof_pic_form').submit(); 
        } 
    } 
});
</script>

主题和教程的其他主题。

What does enctype='multipart/form-data' mean?
http://www.tizag.com/phpT/fileupload.php

此外,PHP值的名称将是name属性,而不是class,因此请使用pic_upload进行查找。