How to upload file using jquery ajax and php (with

2019-07-27 04:21发布

I have a form like this:

<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>

I want that when the user will selects an image, it would be automatically submitted to my PHP page so that I can save it in the database and return an insert_id with the thumbnail of the picture.

I want to do it using jQuery but not able to do so.

PHP code is:

1条回答
虎瘦雄心在
2楼-- · 2019-07-27 05:02

Easy, use a change trigger on your input Element and do an ajax-request inside:

$("#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.");         
        }
    });   
});

Create a url or route and enter it at url: tag (domain/file.php) and then code serversided stuff:

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();
}
查看更多
登录 后发表回答