txcloud_upload.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. // 请求用到的参数
  2. var prefix='';
  3. if(!tx_domain_url){
  4. var protocol = location.protocol === 'https:' ? 'https:' : 'http:';
  5. prefix= protocol + '//' + tx_bucket + '.cos.' + tx_region + '.myqcloud.com/';
  6. }else{
  7. prefix=tx_domain_url;
  8. }
  9. // 对更多字符编码的 url encode 格式
  10. var camSafeUrlEncode = function (str) {
  11. return encodeURIComponent(str)
  12. .replace(/!/g, '%21')
  13. .replace(/'/g, '%27')
  14. .replace(/\(/g, '%28')
  15. .replace(/\)/g, '%29')
  16. .replace(/\*/g, '%2A');
  17. };
  18. // 计算签名
  19. var getAuthorization = function (options, callback) {
  20. // var url = 'http://127.0.0.1:3000/sts';
  21. var url = '/txcloud_server/sts.php';
  22. var xhr = new XMLHttpRequest();
  23. xhr.open('GET', url, true);
  24. xhr.onreadystatechange = function (e) {
  25. if (xhr.readyState === 4) {
  26. if (xhr.status === 200) {
  27. var credentials;
  28. try {
  29. credentials = (new Function('return ' + xhr.responseText))().credentials;
  30. } catch (e) {}
  31. if (credentials) {
  32. callback(null, {
  33. XCosSecurityToken: credentials.sessionToken,
  34. Authorization: CosAuth({
  35. SecretId: credentials.tmpSecretId,
  36. SecretKey: credentials.tmpSecretKey,
  37. Method: options.Method,
  38. Pathname: options.Pathname,
  39. })
  40. });
  41. } else {
  42. console.error(xhr.responseText);
  43. callback('获取签名出错');
  44. }
  45. } else {
  46. callback('获取签名出错');
  47. }
  48. }
  49. };
  50. xhr.send();
  51. };
  52. // 上传文件
  53. var uploadFile = function (file, callback) {
  54. console.log(file);
  55. var file_suffix_arr =/\.[^\.]+$/.exec(file.name); //{0: ".jpg", groups: undefined,index: 3,input: "2-1.jpg",length: 1}
  56. var file_suffix=file_suffix_arr[0]; //.jpg
  57. var now=new Date();
  58. var year = now.getFullYear(); //得到年份
  59. var month = now.getMonth();//得到月份
  60. var date = now.getDate();//得到日期
  61. var hour = now.getHours();//得到小时
  62. var minu = now.getMinutes();//得到分钟
  63. var seconds = now.getSeconds();//得到秒
  64. month = month + 1;
  65. if (month < 10) month = "0" + month;
  66. if (date < 10) date = "0" + date;
  67. if (hour < 10) hour = "0" + hour;
  68. if (minu < 10) minu = "0" + minu;
  69. if (seconds < 10) seconds = "0" + seconds;
  70. var number = Math.ceil(Math.random()*1000); //生成0~1000范围内的随机数
  71. var time = year + month + date+hour+minu+seconds;
  72. var Key = time+"_"+number+file_suffix; // 这里指定上传目录和文件名
  73. getAuthorization({Method: 'POST', Pathname: '/'}, function (err, info) {
  74. var fd = new FormData();
  75. fd.append('key', Key);
  76. fd.append('signature', info.Authorization);
  77. fd.append('Content-Type', '');
  78. info.XCosSecurityToken && fd.append('x-cos-security-token', info.XCosSecurityToken);
  79. fd.append('file', file);
  80. var url = prefix;
  81. var xhr = new XMLHttpRequest();
  82. xhr.open('POST', url, true);
  83. xhr.upload.onprogress = function (e) {
  84. console.log('上传进度 ' + (Math.round(e.loaded / e.total * 10000) / 100) + '%');
  85. };
  86. xhr.onload = function () {
  87. if (Math.floor(xhr.status / 100) === 2) {
  88. var ETag = xhr.getResponseHeader('etag');
  89. callback(null, {url: prefix + camSafeUrlEncode(Key).replace(/%2F/g, '/'), ETag: ETag,filename:Key});
  90. } else {
  91. callback('文件 ' + Key + ' 上传失败,状态码:' + xhr.status);
  92. }
  93. };
  94. xhr.onerror = function () {
  95. callback('文件 ' + Key + ' 上传失败,请检查是否没配置 CORS 跨域规则');
  96. };
  97. xhr.send(fd);
  98. });
  99. };