如何获取输入类型'文件'在JQuery页面上变量,然后将变量和文件传递给PHP页面进行上传

时间:2016-07-08 07:15:59

标签: php jquery

使用HTML,Javascript和PHP,图片上传功能正常运行。但现在我正在尝试将其转换为HTML,JQuery和PHP,但我无法使用下面的代码上传照片。

我无法在.js页面上获取文件类型变量,然后在php页面上文件本身(upload_p.php)

请告知我做错了什么。我试着让这项工作持续2天,但没有运气。

upload.php的

<form name="Uform" id="Uform" novalidate>
<div class="control-group form-group">
    <input type="file" name="img" id="img">
    <div id="success"></div>
    <button type="submit" class="btn btn-primary">Upload</button>
</div>
</form>

upload.js

$(function() {

$("#UForm file").jqBootstrapValidation({
    preventSubmit: true,
    submitSuccess: function($form, event) {
        event.preventDefault(); 

        // Try #1
        var form   = new FormData() ;
        var file = $('#img')[0].files[0];
        formData.append("file", file);

        // Try #2
        var FileData = $('#img').prop('files')[0];   
        var form_data = new FormData();                  
        form_data.append('file', FileData);


        $.ajax({
            url: "./user/upload_.php",
            type: "POST",
            data: {

                // Try #1
                upload : 1,
                data : file

                // Try #2
                img: img,
            },
            cache: false,
        })
    },
});

upload_p.php

$str_photo = "";
if(isset($_FILES['img'])) { $str_photo = trim($_FILES['img']['name']); }
.
.    
UploadFile($_FILES["img"]["tmp_name"],$str_img_path);
.
.
SQL Query to insert data into database table
.
.
$response['status']='SUC';
$response['message']="Image uploaded successfully";
echo json_encode($response);
return;

1 个答案:

答案 0 :(得分:0)

使用以下ajax代码

.ajax({
    url: "./user/upload_.php",
    data: {

            // Try #1
            upload : 1,
            data : file

            // Try #2
            img: img,
        },
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        alert(data);
    }
});

之后尝试

print_r($_FILES);

upload_.php