上传选择的文件后立即形象 [英] Upload image immediately after file is chosen

查看:93
本文介绍了上传选择的文件后立即形象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何上传影像后立即用户选择从浏览器中的文件?

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

像在Facebook中,当你需要上传你的封面或资料图片,你需要 选择文件并上传启动后。

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"/>

和可以运行函数文件后捞起JS

and js that can run the function after file is picked

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

但我怎么能发送数据,这种方式到PHP?

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

推荐答案

您可以上传使用Ajax文件为Base64字符串(没有被刷新)。 有些事情是这样的。

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 */
}

指这个答案存储的base64磁盘<一href="http://stackoverflow.com/questions/17810501/php-get-base64-img-string-de$c$c-and-save-as-jpg-resulting-empty-image">base64字符串到图像文件

在PHP一些这样的事

<?php

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

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

?>

这篇关于上传选择的文件后立即形象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆