时空网前端
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.

73 lines
1.8 KiB

  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. uni.uploadFile({
  30. url: url + url_a,//开发者服务器 url
  31. filePath: filePath,//要上传文件资源的路径
  32. name: 'image',
  33. formData: {
  34. token: uni.getStorageSync('userinfo').token
  35. },
  36. success: function (res) {
  37. console.log('上传文件...', res)
  38. if (res.statusCode != 200 || !res.data) {
  39. failc(new Error('上传错误:' + JSON.stringify(res)))
  40. return;
  41. }
  42. let res_data = JSON.parse(res.data);
  43. successc && successc(res_data.data);
  44. },
  45. fail: function (err) {
  46. failc(err);
  47. },
  48. })
  49. }
  50. // 获取当前日期(年-月-日),并不足十位补零
  51. function formatTime(date) {
  52. const year = date.getFullYear()
  53. const month = date.getMonth() + 1
  54. const day = date.getDate()
  55. const hour = date.getHours()
  56. const minute = date.getMinutes()
  57. const second = date.getSeconds()
  58. return [year, month, day].map(formatNumber).join('-')
  59. // + ' ' + [hour, minute, second].map(formatNumber).join(':')
  60. }
  61. const formatNumber = n => {
  62. n = n.toString()
  63. return n[1] ? n : '0' + n
  64. }
  65. module.exports = {
  66. uploadFile
  67. };