onchange 上傳照片後 append 產生一個區塊?

asys0512
  • 2.7k
$('body').on('change', '.add-btn',function(e){


    var id = $('.admin-upload-inline').length + 1;
    var iconLayout = $('<div class="admin-upload-inline add-btn pointer" id="icon-layout-'+id+'">');
    var fileInput = $(
      '<input type="hidden" id="file'+id+'" name="icon[]" class="admin-upload" value="">'
    + '<img src="../images/30.png" id="pre'+id+'" class="admin-upload-review">');

    iconLayout.append(fileInput);
    $(".addend-display").append(iconLayout);

    console.log(id);
    var reader = new FileReader();
    reader.onload = function(e) {
      $('#pre' + id).attr('src', e.target.result);
      $('#file' + id).attr('value', e.target.result);

      console.log(e.target.result);
      reader.readAsDataURL($('#file'+id));
    }
<div class="admin-upload-inline add-btn pointer">
        <input type="file" id="file1" name="icon[]" class="admin-upload" accept="image/jpeg, image/png, image/jpg">
        <img src="../images/30.png" id="pre1" class="admin-upload-review">
        <i class="material-icons upload_cover_icon admin-upload-icon-add">add_circle_outline</i>
      </div>

      <div class="addend-display">

      </div>

請問如何當我按下 add-btn 後,圖片能夠經由 FileReader 產生的base64直接丟到我生成過的 隱藏欄位和 img裡面?我發現我都抓不到 data64.....

補充!

foreach ($_POST['icon'] as $value) {
      echo $value;
      preg_match('/^(data:\s*image\/(\w+);base64,)/', $value, $result);
        $file_ext = '.'.$result[2];
        file_put_contents('../../images/product/'.md5(time()).$file_ext, base64_decode(str_replace($result[1], '', $value)));
    }
怎麼都下載不到全部的 base64,都是只有抓到最後一個?
评论
阅读 856
1 个回答
✓ 已被采纳

readAsDataURL应该在onload事件外面

var fileReader = new FileReader(),
    file = input.files[0],
    fileType = file.type;
fileReader.onload = function(){
    if(/^image/.test(fileType)){
        
    }
}
fileReader.readAsDataURL(file);
撰写回答

登录后参与交流、获取后续更新提醒

宣传栏