1. 程式人生 > >wangeditor上傳圖片到阿里雲oss

wangeditor上傳圖片到阿里雲oss

之前文章有寫過laravel上傳圖片到oss, 原理一樣

首先下載php後臺qian簽名js直傳

目錄拷貝以及qi簽名可以檢視之前的文章,主要記錄下wangeditorshan上傳

首先拷貝一份upload.js命名為wangeditor.js

然後加入wangeditor

var E = window.wangEditor
var editor = new E('#content')
editor.customConfig.zIndex = 0
editor.customConfig.uploadImgHeaders = {
    'X-CSRF-TOKEN': $('input[name="_token"]').val()
}
//editor.customConfig.uploadImgServer = '/backend/updetails'
//editor.customConfig.uploadFileName = 'wangpic[]'
//editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024


editor.customConfig.onchange = function (html) {
    $('.wangeditor_value').val(html)
};

editor.create();

修改upload

var uploader = new plupload.Uploader({
	runtimes : 'html5,flash,silverlight,html4',
	browse_button : editor.imgMenuId, 
  multi_selection: true,
  auto_start: true,
	flash_swf_url : '../plupload/js/Moxie.swf',
	silverlight_xap_url : '../plupload/js/Moxie.xap',
  url : 'http://oss.aliyuncs.com',

  filters: {
      mime_types : [ //只允許上傳圖片和zip,rar檔案
      { title : "Image files", extensions : "jpg,gif,png,bmp" }, 
      { title : "video files", extensions : "mp4,3gp" }
      ],
      max_file_size : '10mb', //最大隻能上傳10mb的檔案
      prevent_duplicates : false //不允許選取重複檔案
  },

	init: {
		PostInit: function() {
      set_upload_param(uploader, '', false);
      return false;
    },

    BeforeUpload: function(up, file) {
      set_upload_param(up, file.name, true);
    },

    FilesAdded: function(up) {
      up.start(); //選擇完後直接上傳
    },

		FileUploaded: function(up, file, info) {
      if (info.status == 200)
      {
        editor.cmd.do('insertHtml', '<img src="' + host + g_object_name + '" style="width: auto; max-width:100%;"/>');
        console.log(g_object_name);
      }
      else
      {
        alter(info.response);
      } 
    },

    Error: function(up, err) {
      if (err.code == -600) {
          alter("\n選擇的檔案太大了,可以根據應用情況,在upload.js 設定一下上傳的最大大小");
      }
      else if (err.code == -601) {
          alter("\n選擇的檔案字尾不對,可以根據應用情況,在upload.js進行設定可允許的上傳檔案型別");
      }
      else if (err.code == -602) {
          alter("\n這個檔案已經上傳過一遍了");
      }
      else 
      {
         alter("\nError xml:" + err.response);
      }
    }
	}
});

使用upload

editor.config.customUploadInit = uploader.init(); 

最終的upload.js如下


accessid = ''
accesskey = ''
host = ''
policyBase64 = ''
signature = ''
callbackbody = ''
filename = ''
key = ''
expire = 0
g_object_name = ''
g_object_name_type = 'random_name'
now = timestamp = Date.parse(new Date()) / 1000; 
details_dir = 'details'
currentUrl = window.location.href;
backendIndex = currentUrl.indexOf('backend');
baseBackend = currentUrl.substr(0, backendIndex);

var E = window.wangEditor
var editor = new E('#content')
editor.customConfig.zIndex = 0
editor.customConfig.uploadImgHeaders = {
    'X-CSRF-TOKEN': $('input[name="_token"]').val()
}
//editor.customConfig.uploadImgServer = '/backend/updetails'
//editor.customConfig.uploadFileName = 'wangpic[]'
//editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024


editor.customConfig.onchange = function (html) {
    $('.wangeditor_value').val(html)
};

editor.create();

function send_request()
{
    var xmlhttp = null;
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  
    if (xmlhttp!=null)
    {
        serverUrl = baseBackend + 'backend/getoss/' + details_dir
        xmlhttp.open( "GET", serverUrl, false );
        xmlhttp.send( null );
        return xmlhttp.responseText
    }
    else
    {
        alert("Your browser does not support XMLHTTP.");
    }
};


function get_signature()
{
    //可以判斷當前expire是否超過了當前時間,如果超過了當前時間,就重新取一下.3s 做為緩衝
    now = timestamp = Date.parse(new Date()) / 1000; 
    if (expire < now + 3)
    {
        body = send_request()
        var obj = eval ("(" + body + ")")
        host = obj['host']
        policyBase64 = obj['policy']
        accessid = obj['accessid']
        signature = obj['signature']
        expire = parseInt(obj['expire'])
        callbackbody = obj['callback'] 
        key = obj['dir']
        return true;
    }
    return false;
};

function random_string(len) {
  len = len || 32;
  var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
  var maxPos = chars.length;
  var pwd = '';
  for (i = 0; i < len; i++) {
      pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function calculate_object_name(filename)
{
    suffix = get_suffix(filename)
    g_object_name = key + random_string(20) + suffix
    return ''
}

function set_upload_param(up, filename, ret)
{
    if (ret == false)
    {
        ret = get_signature()
    }
    g_object_name = key;
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename)
    }
    new_multipart_params = {
        'key' : g_object_name,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //讓服務端返回200,不然,預設會返回204
        'callback' : callbackbody,
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
}


var uploader = new plupload.Uploader({
	runtimes : 'html5,flash,silverlight,html4',
	browse_button : editor.imgMenuId, 
  multi_selection: true,
  auto_start: true,
	flash_swf_url : '../plupload/js/Moxie.swf',
	silverlight_xap_url : '../plupload/js/Moxie.xap',
  url : 'http://oss.aliyuncs.com',

  filters: {
      mime_types : [ //只允許上傳圖片和zip,rar檔案
      { title : "Image files", extensions : "jpg,jpeg,gif,png,bmp" }, 
      { title : "video files", extensions : "mp4,3gp" }
      ],
      max_file_size : '10mb', //最大隻能上傳10mb的檔案
      prevent_duplicates : false //不允許選取重複檔案
  },

	init: {
		PostInit: function() {
      set_upload_param(uploader, '', false);
      return false;
    },

    BeforeUpload: function(up, file) {
      set_upload_param(up, file.name, true);
    },

    FilesAdded: function(up) {
      up.start(); //選擇完後直接上傳
    },

		FileUploaded: function(up, file, info) {
      if (info.status == 200)
      {
        var file_type = file.type;
        var is_image = file_type.indexOf('image');
        var is_video = file_type.indexOf('video');
        if(is_image > -1) {
          editor.cmd.do('insertHtml', '<img src="' + host + g_object_name + '" style="width: auto; max-width:100%;"/>');
        }
        if(is_video > -1) {
          editor.cmd.do('insertHtml', '<video controls src="' + host + g_object_name + '" style="width: auto; max-width:100%;"></video>');
        }
      }
      else
      {
        alter(info.response);
      } 
    },

    Error: function(up, err) {
      if (err.code == -600) {
          alter("\n選擇的檔案太大了,可以根據應用情況,在upload.js 設定一下上傳的最大大小");
      }
      else if (err.code == -601) {
          alter("\n選擇的檔案字尾不對,可以根據應用情況,在upload.js進行設定可允許的上傳檔案型別");
      }
      else if (err.code == -602) {
          alter("\n這個檔案已經上傳過一遍了");
      }
      else 
      {
         alter("\nError xml:" + err.response);
      }
    }
	}
});

// uploader.init();
editor.config.customUploadInit = uploader.init();