海南旅游项目 前端仓库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.0 KiB

4 years ago
  1. /*
  2. *上传文件
  3. *@param - filePath :图片的本地资源路径
  4. *@param - dir:表示要传到哪个目录下
  5. *@param - successc:成功回调
  6. *@param - failc:失败回调
  7. */
  8. const uploadFile = function (filePath, successc, failc) {
  9. if (!filePath || filePath.length < 9) {
  10. wx.showModal({
  11. title: '图片错误',
  12. content: '请重试',
  13. showCancel: false,
  14. })
  15. return;
  16. }
  17. // 上传的服务器地址
  18. let url = this.API.DEVURL;
  19. if (this.API.DEV == 'prod') {
  20. url = this.API.PRODURL;
  21. }
  22. const url_a = this.API.API_UPPLOAD_APPLY;
  23. // 上传图片的目录
  24. var nowTime = formatTime(new Date());
  25. const dir = 'wxmini/images/' + nowTime + '/';
  26. // 获取上传的文件类型 fileType
  27. let fileTypeIndex = filePath.lastIndexOf('.');
  28. let fileType = filePath.substring(fileTypeIndex);
  29. var accountInfo = wx.getAccountInfoSync();
  30. var autoappid = accountInfo.miniProgram.appId;
  31. var uploadappid = autoappid || 'wx27c51a989127de12';
  32. uni.uploadFile({
  33. url: url + url_a,//开发者服务器 url
  34. filePath: filePath,//要上传文件资源的路径
  35. name: 'image',
  36. header: {
  37. appid: uploadappid,
  38. Authentication: uni.getStorageSync('userinfo').token
  39. },
  40. success: function (res) {
  41. if (res.statusCode != 200 || !res.data) {
  42. failc(new Error('上传错误:' + JSON.stringify(res)))
  43. return;
  44. }
  45. let res_data = JSON.parse(res.data);
  46. successc && successc(res_data.data.path);
  47. },
  48. fail: function (err) {
  49. failc(err);
  50. },
  51. })
  52. }
  53. // 获取当前日期(年-月-日),并不足十位补零
  54. function formatTime(date) {
  55. const year = date.getFullYear()
  56. const month = date.getMonth() + 1
  57. const day = date.getDate()
  58. const hour = date.getHours()
  59. const minute = date.getMinutes()
  60. const second = date.getSeconds()
  61. return [year, month, day].map(formatNumber).join('-')
  62. // + ' ' + [hour, minute, second].map(formatNumber).join(':')
  63. }
  64. const formatNumber = n => {
  65. n = n.toString()
  66. return n[1] ? n : '0' + n
  67. }
  68. module.exports = {
  69. uploadFile
  70. };