upload.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __rest = (this && this.__rest) || function (s, e) {
  8. var t = {};
  9. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  10. t[p] = s[p];
  11. if (s != null && typeof Object.getOwnPropertySymbols === "function")
  12. for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  13. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  14. t[p[i]] = s[p[i]];
  15. }
  16. return t;
  17. };
  18. import { isObject, SuperComponent, wxComponent } from '../common/src/index';
  19. import props from './props';
  20. import config from '../common/config';
  21. const { prefix } = config;
  22. const name = `${prefix}-upload`;
  23. let Upload = class Upload extends SuperComponent {
  24. constructor() {
  25. super(...arguments);
  26. this.externalClasses = [`${prefix}-class`];
  27. this.options = {
  28. multipleSlots: true,
  29. };
  30. this.data = {
  31. classPrefix: name,
  32. prefix,
  33. current: false,
  34. proofs: [],
  35. customFiles: [],
  36. customLimit: 0,
  37. config: {},
  38. files: [],
  39. max: 0,
  40. sizeLimit: 0,
  41. requestMethod: null,
  42. gridItemStyle: '',
  43. column: 4,
  44. };
  45. this.properties = props;
  46. this.controlledProps = [
  47. {
  48. key: 'files',
  49. event: 'success',
  50. },
  51. ];
  52. this.observers = {
  53. files(files) {
  54. this.handleLimit(files, this.data.max);
  55. },
  56. max(max) {
  57. this.handleLimit(this.data.customFiles, max);
  58. },
  59. gridConfig() {
  60. this.updateGrid();
  61. },
  62. };
  63. this.methods = {
  64. onAddTap() {
  65. const { mediaType, source } = this.properties;
  66. if (source === 'media') {
  67. this.chooseMedia(mediaType);
  68. }
  69. else {
  70. this.chooseMessageFile(mediaType);
  71. }
  72. },
  73. chooseMedia(mediaType) {
  74. const { config, sizeLimit, max } = this.data;
  75. wx.chooseMedia(Object.assign(Object.assign({ count: max === 0 ? 9 : max, mediaType }, config), { success: (res) => {
  76. const files = [];
  77. res.tempFiles.forEach((temp) => {
  78. const { size, fileType, tempFilePath, width, height, duration, thumbTempFilePath } = temp, res = __rest(temp, ["size", "fileType", "tempFilePath", "width", "height", "duration", "thumbTempFilePath"]);
  79. if (sizeLimit && size > sizeLimit) {
  80. wx.showToast({ icon: 'none', title: `${fileType === 'image' ? '图片' : '视频'}大小超过限制` });
  81. return;
  82. }
  83. const name = this.getRandFileName(tempFilePath);
  84. files.push(Object.assign({ name, type: this.getFileType(mediaType, tempFilePath, fileType), url: tempFilePath, size: size, width: width, height: height, duration: duration, thumb: thumbTempFilePath, percent: 0 }, res));
  85. });
  86. this.afterSelect(files);
  87. }, fail: (err) => {
  88. this.triggerFailEvent(err);
  89. }, complete: (res) => {
  90. this.triggerEvent('complete', res);
  91. } }));
  92. },
  93. chooseMessageFile(mediaType) {
  94. const { max, config, sizeLimit } = this.properties;
  95. wx.chooseMessageFile(Object.assign(Object.assign({ count: max, type: Array.isArray(mediaType) ? 'all' : mediaType }, config), { success: (res) => {
  96. const files = [];
  97. res.tempFiles.forEach((temp) => {
  98. const { size, type: fileType, path: tempFilePath } = temp, res = __rest(temp, ["size", "type", "path"]);
  99. if (sizeLimit && size > sizeLimit) {
  100. wx.showToast({ icon: 'none', title: `${fileType === 'image' ? '图片' : '视频'}大小超过限制` });
  101. return;
  102. }
  103. const name = this.getRandFileName(tempFilePath);
  104. files.push(Object.assign({ name, type: this.getFileType(mediaType, tempFilePath, fileType), url: tempFilePath, size: size, percent: 0 }, res));
  105. });
  106. this.afterSelect(files);
  107. }, fail: (err) => this.triggerFailEvent(err), complete: (res) => this.triggerEvent('complete', res) }));
  108. },
  109. afterSelect(files) {
  110. this._trigger('select-change', {
  111. files: [...this.data.customFiles],
  112. currentSelectedFiles: [files],
  113. });
  114. this._trigger('add', { files });
  115. this.startUpload(files);
  116. },
  117. };
  118. }
  119. onProofTap(e) {
  120. var _a;
  121. const { index } = e.currentTarget.dataset;
  122. wx.previewImage({
  123. urls: this.data.customFiles.filter((file) => file.percent !== -1).map((file) => file.url),
  124. current: (_a = this.data.customFiles[index]) === null || _a === void 0 ? void 0 : _a.url,
  125. });
  126. }
  127. ready() {
  128. this.handleLimit(this.data.customFiles, this.data.max);
  129. this.updateGrid();
  130. }
  131. handleLimit(customFiles, max) {
  132. while (max !== 0 && customFiles.length - max > 0) {
  133. customFiles.pop();
  134. }
  135. const proofs = [];
  136. customFiles.forEach((item) => {
  137. if (item.type !== 'video') {
  138. proofs.push(item.url);
  139. }
  140. });
  141. this.setData({
  142. customFiles,
  143. proofs,
  144. customLimit: max === 0 ? Number.MAX_SAFE_INTEGER : max - customFiles.length,
  145. });
  146. }
  147. uploadFiles(files) {
  148. return new Promise((resolve) => {
  149. const task = this.data.requestMethod(files);
  150. if (task instanceof Promise) {
  151. return task;
  152. }
  153. resolve({});
  154. });
  155. }
  156. startUpload(files) {
  157. if (typeof this.data.requestMethod === 'function') {
  158. return this.uploadFiles(files)
  159. .then(() => {
  160. files.forEach((file) => {
  161. file.percent = 100;
  162. });
  163. this.triggerSuccessEvent(files);
  164. })
  165. .catch((err) => {
  166. this.triggerFailEvent(err);
  167. });
  168. }
  169. this.triggerSuccessEvent(files);
  170. this.handleLimit(this.data.customFiles, this.data.max);
  171. return Promise.resolve();
  172. }
  173. triggerSuccessEvent(files) {
  174. this._trigger('success', { files: [...this.data.customFiles, ...files] });
  175. }
  176. triggerFailEvent(err) {
  177. this.triggerEvent('fail', err);
  178. }
  179. onFileClick(e) {
  180. const { file } = e.currentTarget.dataset;
  181. this.triggerEvent('click', { file });
  182. }
  183. getFileType(mediaType, tempFilePath, fileType) {
  184. if (fileType)
  185. return fileType;
  186. if (mediaType.length === 1) {
  187. return mediaType[0];
  188. }
  189. const videoType = ['avi', 'wmv', 'mkv', 'mp4', 'mov', 'rm', '3gp', 'flv', 'mpg', 'rmvb'];
  190. const temp = tempFilePath.split('.');
  191. const postfix = temp[temp.length - 1];
  192. if (videoType.includes(postfix.toLocaleLowerCase())) {
  193. return 'video';
  194. }
  195. return 'image';
  196. }
  197. getRandFileName(filePath) {
  198. const extIndex = filePath.lastIndexOf('.');
  199. const extName = extIndex === -1 ? '' : filePath.substr(extIndex);
  200. return parseInt(`${Date.now()}${Math.floor(Math.random() * 900 + 100)}`, 10).toString(36) + extName;
  201. }
  202. onDelete(e) {
  203. const { index } = e.currentTarget.dataset;
  204. this.deleteHandle(index);
  205. }
  206. deleteHandle(index) {
  207. const { customFiles } = this.data;
  208. const delFile = customFiles[index];
  209. this.triggerEvent('remove', { index, file: delFile });
  210. }
  211. updateGrid() {
  212. let { gridConfig = {} } = this.properties;
  213. if (!isObject(gridConfig))
  214. gridConfig = {};
  215. const { column = 4, width = 160, height = 160 } = gridConfig;
  216. this.setData({
  217. gridItemStyle: `width:${width}rpx;height:${height}rpx`,
  218. column: column,
  219. });
  220. }
  221. };
  222. Upload = __decorate([
  223. wxComponent()
  224. ], Upload);
  225. export default Upload;