2015-05-11 328 views
-1

我需要使用ajax上传图片。详细阐述我的观点: 我需要将我的图像数据传递给PHP页面,并检查文件的类型,大小,名称和所有其他属性。如果所有的属性匹配,那么只有我需要传输文件。这里的问题是数据的传递只能以JSON(AJAX)格式完成。更重要的是,我不必将其转换为base64。使用ajax上传图片(json)

如果你能帮助我,你是最受欢迎的。

在此先感谢。

+0

你到目前为止尝试了什么?无论如何,你可以通过ajax作为* base64 *字符串发送你的图像 – kosmos

+0

我不必将它转换为base 64 @kmsdev –

+1

如果你打算用JSON传递它,你别无选择,只能用base64。 – Misunderstood

回答

1

SO中的想法是处理OP当前代码。我的意思是,我们不是在这里做所有的工作,因为它应该有一个价格。无论如何,这里是你的问题的解决方法:

使用JavaScript将图像转换为base64。这个有用的方法就像一个魅力:

// Code taken from MatthewCrumley (http://stackoverflow.com/a/934925/298479) 
function getBase64Image(img) { 
    // Create an empty canvas element 
    var canvas = document.createElement("canvas"); 
    canvas.width = img.width; 
    canvas.height = img.height; 

    // Copy the image contents to the canvas 
    var ctx = canvas.getContext("2d"); 
    ctx.drawImage(img, 0, 0); 

    // Get the data-URL formatted image 
    // Firefox supports PNG and JPEG. You could check img.src to guess the 
    // original format, but be aware the using "image/jpg" will re-encode the image. 
    var dataURL = canvas.toDataURL("image/png"); 

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); 
} 

然后,只需将返回的字符串为Base64通过Ajax:

$.ajax({ 
    url: 'path/to/your/script.php', 
    type: 'post', 
    data: { paramName: imagedata } // the returned data from above js method, 
    /*...*/ 
}); 

而且,在PHP端,只需将字符串返回到图像文件:

// Code taken from Austin Brunkhorst (http://stackoverflow.com/a/15153931/3648578) 
function base64_to_jpeg($base64_string, $output_file) { 
    $ifp = fopen($output_file, "wb"); 

    $data = explode(',', $base64_string); 

    fwrite($ifp, base64_decode($data[1])); 
    fclose($ifp); 

    return $output_file; 
} 
+0

谢谢@kmsdev。我会试试这个,让你知道更新。 –

+0

不客气,希望你能实现它。注意ajax方法,它需要jQuery – kosmos

+0

你的答案适合我。但是现在一些要求已经改变了。所以我修改了代码。但仍然有一些问题。你可以看看它 - [http://stackoverflow.com/questions/30166082/how-to-fetch-data-from-ajax-in-php] –