简体   繁体   中英

Upload photo in background with ajax

So I'm a bit new to ajax, I just want to see if anyone can help me with this... I have my main page. I'll just put the element I'm working with so I don't have to put the whole page.

<input type="file" id="myphoto" />

Then, instead of submitting it, what I want to do is run it through a javascript function with an ajax form in it like this

$.ajax({
    type: "POST",
    url: "myphppage.php",
    "Whatever other code needed"
})

to upload the photo. Then, the form URL could be a php page that moves the photo to a different directory. I hope you know what I mean. Any help would be greatly appreciated...

first make a html file which select the file from anywhere, like

uplaod.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX UPLOAD</title>
</head>
<body>
<form enctype="multipart/form-data">
    <input id="file" type="file" />
    <input type="button" id="upload" value="Upload" />
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="upload.js"></script>
</html>

now, make js file like below,

upload.js

$(document).ready(function() {
$('#upload').on('click', function() {
var file_data = $('#file').prop('files')[0];   
var form_data = new FormData();                  
form_data.append('file', file_data);

$.ajax({
            url: 'upload.php', 
            dataType: 'text',  
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,                         
            type: 'post',
            success: function(data){
                alert(data); 
            }
 });
});
});

now, make a directory uploads and a php file which upload the file to upload directory

upload.php

<?php

if (0 < $_FILES['file']['error']) {
    echo 'Error: ' . $_FILES['file']['error'] . '<br>';
} else {
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    echo "success";
}

XHR2 AJAX request can submit binary data like images:

DEMO

However, changing the address bar (windows.location) will interrupt the upload as the new page is loaded. You can work around of this by loading pages via AJAX and using History API:

Demo1

Those who have the common sense and/or enough brain to avoid gayQuery...

function uploadFile(){
    var form_data = new FormData();
    var first_file = document.getElementById('your_input_element_which_type_is_file').files[0];
    var link = 'file_upload.php'; /*or which ever you have, maybe add ?params=xxx&other_params=yyyy */
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            var response = xmlhttp.responseText;
            /* check your custom response here */
            }
            /* check other errors here too */
        }
    form_data.append('file', first_file);
    xmlhttp.open('POST', link, true);
    xmlhttp.send(form_data);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM