-1

I have a form in html and a upload file control

<form action="action.php" method="post" enctype="multipart/form-data"> 
  <input type="file" name="file">   
  <input type="submit" value="submit"> 
</form>

I want to get the byte content of the image "base64_encode()" without uploading the file to the server

Arturs
  • 1,258
  • 5
  • 21
  • 28
  • How do you expect to get any information about the image unless it's read by the server? You probably mean you want it to be uploaded but not saved to the server. –  Aug 28 '13 at 11:39
  • If you want to do it without saving the uploaded file to server, then you must parse the multipart data manually which is not trivial. – fardjad Aug 28 '13 at 11:40
  • my requirement suggest to store the file to different server, but i want the byte content of the file. – user2613027 Aug 28 '13 at 11:40
  • @fardjad how can we do that – user2613027 Aug 28 '13 at 11:43

3 Answers3

0

You can try using the HTML5 :

Create a canvas, load your image into it and then use toDataURL() to get the base64 representation.

Note: Not tested

Edit:

http://tutorials.jenkov.com/html5-canvas/todataurl.html

Jack Daniel's
  • 2,583
  • 22
  • 28
  • Definitely a good way IF the browser your visitors are using supports the Canvas feature. No backwards compatibility. None the less the closest answer to what the OP expects! :) – Sunny R Gupta Aug 28 '13 at 12:13
0

Here you go, not compatible with older IE for sure, not 100 correct since it's not handling multiple files correctly (you need unique id-s for the img and the canvas), but...

<html>
    <body>
    <input type="file" id="files" name="files[]" multiple />
    <output id="list"></output>

<script>
function handleFileSelect(evt) {
    var files = evt.target.files;
    for (var i = 0, f; f = files[i]; i++) 
    {
        if (!f.type.match('image.*')) 
        continue;

    var reader = new FileReader();

    reader.onload = (function(theFile)
    {
        return function(e) {
            var span = document.createElement('span');
            span.innerHTML = ['<img id="ex1" src="', e.target.result, '" title="', escape(theFile.name), '"/>'].join('');
            document.getElementById('list').insertBefore(span, null);

            var img  = document.getElementById("ex1");

            var canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;

            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0);

            var dataUrl = canvas.toDataURL();
            alert(dataUrl);

            };
        })(f);
        reader.readAsDataURL(f);
    }
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
    </body>
</html>
sanyi
  • 5,999
  • 2
  • 19
  • 30
  • Will not work for all browser, 0 backward compatibility with non CANVAS supporting browsers. – Sunny R Gupta Aug 28 '13 at 12:23
  • I am not in position to use html 5. – user2613027 Aug 28 '13 at 12:24
  • Well, OK, you should specify the constraints in the question you asked, so people avoid spending time for unintended solutions. – sanyi Aug 28 '13 at 12:26
  • hey sorry mate, but can we do that in php n html – user2613027 Aug 28 '13 at 12:32
  • PHP is server side, you want to transfer the image without upload, so no server side code (PHP) involved, in HTML I don't know anything else. Or maybe you say, without saving the file to the server disk, just convert it on the fly? – sanyi Aug 28 '13 at 12:36
  • @sanyi can u tell me how to convert the image to its byte content on the fly – user2613027 Aug 28 '13 at 12:49
  • On client (HTML) side you have my solution, on server (side) you can go with either fardjad or Sunny answer. When you post that file that file is uploaded, stored in a temporally directory by the server and handled to PHP to do as he wants. More than that is possible only if you control the server (say apache) code, and you don't. – sanyi Aug 28 '13 at 12:55
-1

The following is taken from this answer:

$raw_data = file_get_contents('php://input');
$boundary = substr($raw_data, 0, strpos($raw_data, "\r\n"));

// Fetch each part
$parts = array_slice(explode($boundary, $raw_data), 1);
$data = array();
$base64_encoded = NULL;

foreach ($parts as $part) {
    // If this is the last part, break
    if ($part == "--\r\n") break; 

    // Separate content from headers
    $part = ltrim($part, "\r\n");
    list($raw_headers, $body) = explode("\r\n\r\n", $part, 2);

    // Parse the headers list
    $raw_headers = explode("\r\n", $raw_headers);
    $headers = array();
    foreach ($raw_headers as $header) {
        list($name, $value) = explode(':', $header);
        $headers[strtolower($name)] = ltrim($value, ' '); 
    } 

    // Parse the Content-Disposition to get the field name, etc.
    if (isset($headers['content-disposition'])) {
        $filename = null;
        preg_match(
            '/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/', 
            $headers['content-disposition'], 
            $matches
        );
        list(, $type, $name) = $matches;
        isset($matches[4]) and $filename = $matches[4]; 

        // handle your fields here
        switch ($name) {
            // this is a file upload
            case 'userfile':
                 $base64_encoded = base64_encode($body);
                 break;

            // default for all other files is to populate $data
            default: 
                 $data[$name] = substr($body, 0, strlen($body) - 2);
                 break;
        } 
    }
}

echo $base64_encoded;

WARNING:

The code above uses substr() to search for boundaries and gets field names via regular expressions.

If you want to do this more efficiently, you must implement a fast string searching algorithm like Boyer-Moore

It stores the whole content in memory. You may want to limit the maximum upload size, etc.

Community
  • 1
  • 1
fardjad
  • 20,031
  • 6
  • 53
  • 68
  • Doing these intensive computations while storing the entire file in memory would not be the best way forward if you are looking at scalability. Consider 100 people trying to upload the files at once, that means 100 images currently reside in your RAM which could otherwise have been free to handle other requests from clients. (Also, I am not the downvoter.) – Sunny R Gupta Aug 28 '13 at 12:12
  • @SunnyRGupta [`base64_encode()`](http://php.net/manual/en/function.base64-encode.php) takes a string. So encoding the uploaded file using `base64_encode()` requires the resembled multipart content to be stored on memory (as string). That's what OP asked. I warned him/her anyways. – fardjad Aug 28 '13 at 12:19
  • i just want to convert the image to its byte content to that i will be send it to the web service. – user2613027 Aug 28 '13 at 12:47
  • @SunnyRGupta this eats exactly the same memory as reading it from the file and store it once as binary and once as base64, in other words is not really different than your solution. On the other hand, underneath I am almost sure that the server creates the temporally file anyway. – sanyi Aug 28 '13 at 12:48