upload.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import {
  2. uploadImg,
  3. finishUpload
  4. } from '@/api/common.js';
  5. import crypto from 'crypto-js';
  6. import {
  7. Base64
  8. } from 'js-base64';
  9. export const upload = function(r,operate) {
  10. return new Promise((resolve,reject)=>{
  11. let suffix = r.url.split('.')[1]
  12. uploadImg({
  13. "fineName": r.url.split('/')[3] + '.' + suffix,
  14. operate
  15. }).then(res => {
  16. if (res.state == 'Success') {
  17. const date = new Date();
  18. date.setHours(date.getHours() + 1);
  19. const policyText = {
  20. expiration: date.toISOString(), // 设置policy过期时间。
  21. conditions: [
  22. // 限制上传大小。
  23. ["content-length-range", 0, 1024 * 1024 * 1024],
  24. ],
  25. };
  26. let fileName = r.name
  27. const host = 'https://' + res.content.bucket + '.' + res.content.endPoint;
  28. const policy = Base64.encode(JSON.stringify(policyText));
  29. const signature = crypto.enc.Base64.stringify(crypto.HmacSHA1(policy, res.content.token
  30. .accessKeySecret));;
  31. const filePath = r.url; // 待上传文件的文件路径。
  32. let paths = res.content.paths[0]
  33. // paths.pop()
  34. uni.uploadFile({
  35. url: host, // 开发者服务器的URL。
  36. filePath: filePath,
  37. name: 'file', // 必须填file。
  38. formData: {
  39. key: paths.join('/'),
  40. policy,
  41. success_action_status: '200', //让服务端返回200,不然,默认会返回204
  42. OSSAccessKeyId: res.content.token.accessKeyId,
  43. signature,
  44. 'x-oss-security-token': res.content.token.securityToken // 使用STS签名时必传。
  45. },
  46. success: (res1) => {
  47. if (res1.statusCode === 200) {
  48. console.log('上传成功');
  49. // 告知服务器上传成功地址
  50. finishUpload(
  51. [{
  52. path: res.content.paths[0],
  53. }]).then(msg => {
  54. resolve(host + '/' + paths.join('/'))
  55. })
  56. }
  57. },
  58. fail: err => {
  59. console.log(err);
  60. }
  61. });
  62. }
  63. })
  64. })
  65. }