Frage

How can I upload a image immediately after user pick a file from browser?

Like in Facebook, when you need to upload your cover or profile image, you need to select file and after that upload starts.

I have for now just my input tag

<input id="chaf" type="file"/>

and js that can run the function after file is picked

$('#chaf').change(function(){
    // Upload image start
});

But how can I send the data to php in this way?

War es hilfreich?

Lösung

You can upload files as a Base64 string using Ajax (without being refreshed). some thing like this.

$(document).on("change", ".custom-file-input", this, function(e){       
   GetBase64( e.target );
});

function GetBase64( input ) {
   if ( input.files && input.files[0] ) {
      var FR= new FileReader();
      FR.onload = function(e) {
         var str = e.target.result;
         /* preview it ( if you wanted to ) */
         $('#preview-img').attr( "src", str );
         /* upload it to server */
         UploadFile(  str );
      };       
      FR.readAsDataURL( input.files[0] );
   }
}

function UploadFile( file_str ) {
   console.log( file_str );
   /* use $.ajax to upload your file */
}

refer this answer for storing base64 in disk base64 string to an image file

in php some thing like this

<?php

$base64Str = $_REQUEST[ "your-post-variable" ];
$img = explode(',', $base64Str);

$fp = fopen( "my-image.png" , "wb"); 
fwrite($fp, base64_decode( $img[1]) ); 
fclose($fp); 

?>

Andere Tipps

You should check out: https://github.com/Widen/fine-uploader. This does exactly what you want. It will start uploading the second they select the image. It allso supports drag& drop and multiple file upload.

Another option - using IaaS for file uploading, such as Uploadcare (this system is maintained by us):

https://uploadcare.com

All you have to do is add the JS library into your header:

<script>
    UPLOADCARE_PUBLIC_KEY = 'PUBLIC-KEY';
    UPLOADCARE_AUTOSTORE = true;
</script>
<script charset="utf-8" src="https://ucarecdn.com/widget/1.4.6/uploadcare/uploadcare-1.4.6.min.js"></script>

and replace file input with specially marked hidden input in your form:

<input type="hidden" role="uploadcare-uploader" name="file_fieldname" />

It will add a widget to the page. Once the file is selected (from local drive, URL, Dropbox/Box/GoogleDrive/Facebook/Instagram/etc.) or dropped onto the widget, upload will start immediately.

The form will send an UUID of the uploaded file to your server, so you can store a reference to it.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top