upload.vue 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <template>
  2. <view></view>
  3. </template>
  4. <script>
  5. export default {
  6. data() {
  7. return {
  8. /*需要返回的图片*/
  9. imageList: []
  10. };
  11. },
  12. onLoad() {},
  13. props: ['num'],
  14. mounted() {
  15. this.chooseImageFunc();
  16. },
  17. methods: {
  18. /*打开相机或者相册,选择图片*/
  19. chooseImageFunc() {
  20. let self = this;
  21. uni.chooseImage({
  22. count: self.$props.num || 9, //默认9
  23. sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
  24. sourceType: ['album', 'camera'], //从相册选择
  25. success: function(res) {
  26. self.uploadFile(res.tempFilePaths);
  27. },
  28. fail: function(res) {
  29. self.$emit('getImgs', null);
  30. },
  31. complete: function(res) {
  32. }
  33. });
  34. },
  35. /*上传图片*/
  36. uploadFile: function(tempList) {
  37. let self = this;
  38. let i = 0;
  39. let img_length = tempList.length;
  40. let params = {
  41. token: uni.getStorageSync('token'),
  42. app_id: self.getAppId()
  43. };
  44. uni.showLoading({
  45. title: '图片上传中'
  46. });
  47. tempList.forEach(function(filePath, fileKey) {
  48. uni.uploadFile({
  49. url: self.websiteUrl + '/api/file.upload/image',
  50. filePath: filePath,
  51. name: 'iFile',
  52. formData: params,
  53. success: function(res) {
  54. let result = typeof res.data === 'object' ? res.data : JSON.parse(res
  55. .data);
  56. if (result.code === 1) {
  57. self.imageList.push(result.data);
  58. } else {
  59. self.showError(result.msg);
  60. }
  61. },
  62. complete: function() {
  63. i++;
  64. if (img_length === i) {
  65. uni.hideLoading();
  66. // 所有文件上传完成
  67. self.$emit('getImgs', self.imageList);
  68. }
  69. }
  70. });
  71. });
  72. }
  73. }
  74. };
  75. </script>
  76. <style></style>