LoginSignup
11
11

More than 5 years have passed since last update.

bootstrap-wysiwygで画像アップロード対応してみた。(fuelphp)

Last updated at Posted at 2014-11-18

bootstrap-wysiwygのダウンロード先: mindmup/bootstrap-wysiwyg

bootstrap-wysiwygの画像挿入はデータURIスキームでテキスト化されているので、
これをアップロードに変更してみた。

1. Rangeの取得

挿入時、キャレット位置に挿入する為、Rangeを取得する。
※editor内を操作したときのみに取得する。

var range = null;

$("#editor").bind("keypress click", function(){
    var sel = document.getSelection();
    range = sel.getRangeAt(0);
});

2.画像のアップロード

ajaxで送信をおこなう
(ファイルとファイルタイトル(任意)を送信)

ajax処理
$.ajax({
    url: $form.attr('action'),
    type: $form.attr('method'),
    contentType: false,
    processData: false,
    data: fd,
    dataType: 'json',
    timeout: 10000,  // 単位はミリ秒

   .....
 });
送信先コード(fuelphp使ってます)
public function action_index(){
     
        $new_name = 'img_'.date('ymtHis');
        $config = array('path' => DOCROOT.'assets/img/upload/',
            'new_name'=>$new_name,
            'ext_whitelist'=> array('jpg','jpeg','gif','png','JPG'));

        \Fuel\Core\Upload::process($config);

        if(\Fuel\Core\Upload::is_valid()){
            \Fuel\Core\Upload::save();
            $files = \Fuel\Core\Upload::get_files();
            foreach ($files as $file){
                 $file_name = preg_replace('/.jpg|.jpeg|.gif|.png|.JPG/', '', $file['name']);;
                $new_name = $new_name.'.'.$file['extension']; 
                break;
            }    
        }else{}
       \Fuel\Core\Input::post('img_title') ? $img_title = \Fuel\Core\Input::post('img_title') : $img_title = $file_name;

       $data = array('url'=>Uri::create('public/assets/img/upload/'.$new_name),'title'=>$img_title);

       //ファイルURLとファイルタイトルをjsonで返す。
       return json_encode($data);
    }

3.画像の挿入 処理

ajax処理
$.ajax({
    ......

    // 通信成功時の処理
    success: function(data) {
        if(!range){
             //Rangeを取得していない場合、(#editorを操作していない場合)
            var code = '<img src="'+data.url+'" title="'+data.title+'"/>';
             //#editorの最後に追加.
            $('#editor').append(code);
        }else{
            //Rangeを取得している場合
            //エレメント生成
            var newNode = document.createElement('img');
            newNode.setAttribute("src", data.url);
            newNode.setAttribute("title", data.title);
            //Rangeの開始境界点に挿入
            range.insertNode(newNode);
        }   
    },
    // 通信失敗時の処理
    error: function(xhr, textStatus, error) {
        alert('ファイル送信に失敗しました。');
    }
 });

無理やり感がありありですが、これでアップロード対応できました(笑)

11
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
11