h5将上传图片转换成base64值

来源:互联网 发布:彩钢瓦承重知多少 编辑:程序博客网 时间:2024/03/29 09:23
  $("#article_image").change(function(){
    var file = this.files[0];
        //判断类型是不是图片  
        if(!/image\/\w+/.test(file.type)){     
                alert("请确保文件为图像类型");   
                return false;   
        }   
        var reader = new FileReader();   
        reader.readAsDataURL(file);   
        reader.onload = function(e){
          image_base64=this.result.split(",")[1];
           //就是base64 
          article_image = image_base64;   
        }

  });

后台接收的时候可以将image_base64传递到后台

ruby语言后台处理

def self.base64_cover_file(base64_code, img_type ='jpg')
    path = Rails.root.join("public", "#{Digest::MD5.hexdigest(SecureRandom.random_number.to_s)}.#{img_type}")
    File.open(path, 'wb') do |f|
      f.write(Base64.decode64(base64_code))
    end

    path.to_s  //这样得到的路径是完整的路径.但是要赋值给对象属性只需要public后面的东西就可以了.所以用的时候根据存储位置处理下.
  end


0 0
原创粉丝点击