weixin_33694172 2015-05-11 09:19 采纳率: 0%
浏览 164

使用Ajax(json)上传图片

I need to upload image using ajax. Elaborating my point: I need to pass my image data to a PHP page and check the type, size, name and all other attributes of the file. If all attributes matches, then only I need to transfer the file. Problem here is passing of data should be done in JSON(AJAX) format only. One more important thing is that I don't have to convert it to base64.

If you can help me in this, You are most welcome.

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • 三生石@ 2015-05-11 10:00
    关注

    The idea in SO is to work on the OP current code. I mean, we are not here to make all the job, because it should have a price. Anyway, here is a workaround for your issue:

    Convert your image to base64 using javascript. This useful method works like a charm:

    // 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,/, "");
    }
    

    Then just pass the returned string as base64 through ajax:

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

    And, in PHP side, just return the string to an image file:

    // 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; 
    }
    
    评论

报告相同问题?