使用Ajax和Javascript保存base64图像

时间:2014-05-07 10:22:59

标签: javascript php jquery ajax base64

我试图通过ajax和FileReader使用base64解码保存/上传图像。照片正在显示,但在指定目的地时无法保存。有人可以帮忙吗?

代码:

HTML

<input type="file" id="choose" multiple="multiple" />

JS

function readImage(file) {

    var reader = new FileReader();
    var image  = new Image();

    reader.readAsDataURL(file);
    reader.onload = function(_file) {
        image.src    = _file.target.result;
        image.onload = function() {
            var w = this.width,
                h = this.height,
                t = file.type,
                n = file.name,
                s = ~~(file.size/1024) +'KB';
            $('#uploadPreview').append('<img src="'+ this.src +'"><br>');
        };
        image.onerror= function() {
            alert('Invalid file type: '+ file.type);
        };
    };

}
$("#choose").change(function (e) {
    if (this.disabled) return alert('File upload not supported!');
    var F = this.files;
    if (F && F[0]) for(var i=0; i<F.length; i++) readImage( F[i] );
    $.each(this.files, function(index, file) {
        $.ajax({
            url: "upload.php",
            type: 'POST',
            data: {filename: file.filename, data: file.data},
            success: function(data, status, xhr) {}
        });
    });
    files = [];
});

PHP

<?php
function uploadimg() {

    $error = false;
    //if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
    //$upload_overrides = array( 'test_form' => false );
    $images=array();

    $a=0;
    unset ($_POST['action']);

    foreach($_POST as $basefile){


        $upload_dir       = wp_upload_dir();
        $upload_path      = str_replace( '/', DIRECTORY_SEPARATOR, $upload_dir['path'] ) . DIRECTORY_SEPARATOR;
        $base64_string = $basefile;
        echo $basefile;
        $base64_string = preg_replace( '/data:image\/.*;base64,/', '', $base64_string );
        $decoded_string= base64_decode($base64_string); // 0 bytes written in fwrite
        $source = imagecreatefromstring($decoded_string); // 0 bytes written in fwrite
        $output_file = $upload_path.'myfilef'.$a.'.jpg';
        $images[]=$output_file;
        $a++;
        $image = fopen( $output_file, 'wb' );

        $bytes=fwrite( $image, $source);
        echo $bytes;
        fclose( $image );
    }
    echo json_encode($images);
    exit;

}

add_action('wp_ajax_uploadimg', 'uploadimg');
add_action('wp_ajax_nopriv_uploadimg', 'uploadimg');
?>

寻求帮助。

0 个答案:

没有答案