如何使用jQuery AJAX和PHP上传文件(不点击任何提交按钮)(How to upload f

2019-10-19 05:41发布

我有这样的形式:

<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代码:

Answer 1:

很简单,用你的输入元素的变化触发和内部做一个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,路线,并在网址输入:标签(域/ file.php),然后代码serversided的东西:

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();
}


文章来源: How to upload file using jquery ajax and php (without clicking any submit button)