如何使用jquery ajax和php上传文件(不点击任何提交按钮)

时间:2014-01-16 14:41:28

标签: javascript php jquery ajax file-upload

我有一个这样的表格:

<form method="post" class="form_cnvc">
   <p><input type="text" name="f_nm" value="" placeholder="type your first name"></p>
   <p><input type="text" name="l_nm" value="" placeholder="type your last name"></p>
   <div class="dropfile visible-lg">
   <input type="file" id="image_file_input" name="image_file_input">
   <span>Select Images(.jpg , .png, .bmp files) </span>
   </div>
   <p class="submit"><input type="submit" name="submit" value="post"></p>
 </form>

我希望当用户选择图像时,它会自动提交到我的PHP页面,以便我可以将其保存在数据库中并返回带有图片缩略图的insert_id。

我想使用jQuery但不能这样做。

PHP代码是:

1 个答案:

答案 0 :(得分:5)

很简单,在输入元素上使用更改触发器并在内部执行ajax请求:

$("#image_file_input").change(function() { 
    $.ajax({
        url: "my-target-url.php",
        type: "post",
        dataType: 'json',
        processData: false,
        contentType: false,
        data: {file: $("#image_file_input").val()},
        success: function(text) {
            if(text == "success") {
                alert("Your image was uploaded successfully");
            }
        },
        error: function() {
            alert("An error occured, please try again.");         
        }
    });   
});

创建一个网址或路由,然后在url:tag(domain / file.php)输入,然后编写服务器代码:

function processFileUpload() {
    if(count($_FILES) > 0) {
        foreach($_FILES as $file) {
            //DO whatever you want with your file, save it in the db or stuff...
            //$file["name"];
            //$file["tmp_name"];
            //Insert here bla blubb
            echo "success";
        }
    }
    die();
}