upload.js 9.9 KB

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