如何在PHP中使用Ajax上传图像?

时间:2011-12-27 04:24:36

标签: php jquery

我有一张表格

<form id="profile_imageform" class="image_form" enctype="multipart/form-data">

    <fieldset>
        <div class="entry">
            <label>Filename:</label>
            <input type="file" name="file" id="file" />
        </div>
    </fieldset>
    <div class="actions">
        <button type="submit">Save &amp; Close</button>( <a href="#/profile" class="cancel">Cancel</a> )
    </div>
</form>

和我的js文件看起来像

  

ProfileForm.prototype.init = function(){           var self = this;

    //Initialize properties
    this.view = $( "#profile_form_view" );
    this.imageForm = $( "#profile_imageform" );
    this.fields.id = this.imageForm.find( ":input[ name = 'id' ]" );
    this.fields.image = this.imageForm.find( ":input[ name = 'file' ]" );

    //Bind the submit handler
    this.imageForm.submit(function( event ){

        //Submit the form
        self.saveImage(this.fields.id.val(), this.fields.image.val());

        //Cancel default event
        return( false );

    });

 ProfileForm.prototype.saveImage = function( id, image, onSuccess, onError ){
    var self = this;

    application.ajax({
        url: "test.php",
        data: {
            method: "saveImage",
            id: id,
            image: image
        },
        success: function( response ){
            if (response.success){
                onSuccess( response.data );
            }else{
                onError( response.errors );
            }
        }

    });
};

this.fields.image.val() 

返回我需要的图像名称是tmp_name。 是否可以在jQuery中获取它的tmp_name?如果是这样的话?

但是这个php代码也会返回错误

if (isset($_POST['method']))
{
    if (isset($_POST['image']))
    {
        echo $_FILES['image']['tmp_name'];
    }
}

2 个答案:

答案 0 :(得分:3)

如果您没有进行任何错误检查,请不要期待错误响应....

function file_upload_error_message($error_code) {
    switch ($error_code) {
    case UPLOAD_ERR_INI_SIZE:
        return 'The uploaded file exceeds the upload_max_filesize directive in    php.ini';
    case UPLOAD_ERR_FORM_SIZE:
        return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
    case UPLOAD_ERR_PARTIAL:
        return 'The uploaded file was only partially uploaded';
    case UPLOAD_ERR_NO_FILE:
        return 'No file was uploaded';
    case UPLOAD_ERR_NO_TMP_DIR:
        return 'Missing a temporary folder';
    case UPLOAD_ERR_CANT_WRITE:
        return 'Failed to write file to disk';
    case UPLOAD_ERR_EXTENSION:
        return 'File upload stopped by extension';
    default:
        return 'Unknown upload error';
}
} 

答案 1 :(得分:1)

您可以使用JQuery文件上传插件脚本 - Uploadify

http://www.uploadify.com/demos/

http://www.uploadify.com/documentation/