image upload with ajax and php

五迷三道 提交于 2019-11-30 07:42:55

You can't upload files through AJAX. You need to work with IFRAMEs or a Flash-Based uploader.

Actualy you can upload images with the ajax function in Jquery in atleast the lates version of chrome.

HTML:

<form action="/" enctype="multipart/form-data" method="post" accept-charset="utf-8">
     <input type="file" name="image"/>
     <button type="submit">
</form>

JS:

$("form").submit(function(){
    var formData = new FormData($(this)[0]);
    $.ajax({
       url: window.location.pathname,
       type: 'POST',
       data: formData,
       async: false,
       cache: false,
       contentType: false,
       processData: false,
       success: function (data) {
              alert(data);
       }
    }); 
    return false;
}); 

This script will send a post request with the created file data to the current page through Ajax. You can change the destination obviously through changing the url parameter.

Try to use JQuery plugin for uploading an image.

May be http://www.uploadify.com/

This will give an idea how to do it.

Assuming you have a handle on the server side.. here is a small function and example on how to implement the 'iframe hack' in javascript.

html

<form name="image-upload">
<input type="file" name="image" /></br>
<button type="submit" name="upload">Upload</button>
<div id="upload-results"></div>
</form>

javascript

var fileUpload = function(form /* HTMLElement */, action /* Form Action URL */, callback /* Callback function */) {
    /* vars */
    var atribs = {
        "target": "upload_iframe",
        "action": action,
        "method": "post",
        "enctype": "multipart/form-data",
        "encoding": "multipart/form-data"
    }, iframe;
    /* iframe listener */
    var ilistener = function() {
        var results;
        listener.remove(this, 'load', ilistener);
        if( 'contentDocument' in this ) {
            results = this.contentDocument.body.innerHTML;
        } else if ( 'contentWindow' in this ) {
            results = this.contentWindow.document.body.innerHTML;
        } else if ( 'document' in this ) {
            results = this.document.body.innerHTML;
        } else {
            throw "i'm dead jim :/";
        }
        callback.apply(this,[results]); // call the callback, passing the results
        this.parentNode.removeChild(this); // remove the iframe
    };

    /* create the iframe */
    form.parentNode.appendChild(FragBuilder([{"tagName": "iframe","id": "upload_iframe","name": "upload_iframe","style": {"height": "0","width": "0","border": "0"}}]));
    /* collect the iframe back */
    iframe = By.id('upload_iframe');
    /* set the form properties */
    for( var attr in atribs ) {
        if( attr in form ) {
            form[attr] = atribs[attr];
        }
    }
    /* attach the event listener to the iframe */
    listener.add(iframe, 'load', ilistener);
    /* submitting the form */
    form.submit();
};

// get the form, and the results area
var form = document.forms['image-upload'], results = By.id('upload-results');
// listen for the form submit, capture it, and run the iframe upload.
listener.add(form, 'submit', function(e) {
    e.preventDefault();
    results.innerHTML = 'Uploading...';
    fileUpload(this, 'server.php' /* really anything */, function(data) { 
        console.log(data);
            results.innerHTML = "Uploaded!";
    });
});

Please note: for simplicity purposes I have used the following utilities. https://github.com/rlemon/FragBuilder.js DocumentFragment builder from JSON input.
https://gist.github.com/2172100 event listener, and By utility functions.
*these are both easily removed.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!