最简单的图像上传功能,无需刷新页面

Here's a challenge:

I don't care about which language to use, Javascript, PHP, .. whatever. I need the most simple way to let my user upload an image. I will later offer the user a way to place it on a canvas (displayed inside a div, with jquery draggable)

I can not have the page refreshed since there are useful variables in other fields etc.. enter image description here

(I don't have any security preferences as this will be a local website for intranet)

I tried:

<form action="upload_file.php" method="post" enctype="multipart/form-data">
            <label for="file">Filename:</label>
            </br>
            <input type="file" name="file" id="file" size="70%"><br>
            </br>
            <input type="submit" name="submit" value="Submit">
            </form>

But then came to realise there are soo many options out there, such as uploadify, and i easily got lost online..

The way that I would suggest is using AJAX and and make your upload box a div which can be replaced when the upload is successful. Instead of traditional post you then create a Javascript function for onSubmit. Your action can then be changed to #.

If you lookup AJAX there are some great tutorials about and you will be able to do many more amazing things.

Alternatively look into jQuery which will definitely have something to help you

You have two choices to make a file upload w/o refreshing the page:

  • Use HTML5 form upload
  • Post the form to an hidden iframe

The latter one gives best browser compatibility, and is what I'd suggest you to use. To post to an hidden iframe, simply set the target of the form to the iframe:

<script>
// Global callback function from the file
function uploadCallback(){
    console.log("File is uploaded!");
}
</script>

<iframe name="hiddentarget" style="display:none;"></iframe>
<form action="upload_file.php" method="post" enctype="multipart/form-data" target="hiddentarget">
    ...

To respond back to the site from the iframe, you will have to go through the window.top frame as such:

upload_file.php:

<?php
// Uploading stuff
// ...

// "Talk" back to the site
// Of course you can (should) pass some parameter to this JS-function, like the filename of the recently uploaded image.
echo "<script>window.top.uploadCallback();</script>";
?>

EDIT: As suggested by other users; the optimal solution would be to use the File API where supported, and fall back to the hidden iframe on browser that doesn't support it. This gives you nice features such as file uploda progress for example.

I'm gonna show you an example on how to use the jQuery Form Plugin to upload files to your server really easy without needing to refresh the page.

First off, download and install the jQuery Form Plugin. After you do that, include it in your files where you want to make use of it. Add an ID attribute to your form tag like this:

id="unique_id"

After you have identified the upload form, put this code in your jQuery:

$(function() {
    $('#unique_id').ajaxForm({
        target: '.myTarget' // Display here whatever the server side script returns
        success: function(response) {
            // An usual success callback
        }
    })
})

Assuming that your server side language is PHP, this is how a simple upload script would look like (upload_file.php):

<?php
$uploaddir = 'your_upload_dir/something';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']); // Filename

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo $uploadfile;
} else {
    echo "Error";
}
?>

Where userfile is the name attribute of your file input (<input type="file" />).

The above code combined returns the relative path to your image which you can use to display the image inside an img tag. You must use Javascript (or jQuery) for that.