choose-file.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /*
  2. * Copyright (C) 2020 Tencent Cloud.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. // #ifdef H5
  17. const inputElement = document.createElement('input');
  18. inputElement.type = 'file';
  19. // #endif
  20. /**
  21. * 选择文件 (仅支持在H5平台运行)
  22. * @async
  23. * @param {string} accept - 允许选择的文件类型,比如'image/*'代表只能选择图片,'image/png'代表只能选择PNG图片等,详情请查阅input元素accept属性的相关文档
  24. * @param {boolean} mutiple - 是否允许选择多个文件
  25. * @return {Promise<File[]>} 返回用户选择的文件列表
  26. */
  27. export default function chooseFile(accept, mutiple) {
  28. return new Promise(async (resolve, reject) => {
  29. // #ifdef H5
  30. inputElement.accept = accept || '';
  31. inputElement.multiple = !!mutiple;
  32. inputElement.onchange = () => {
  33. const files = [...inputElement.files];
  34. inputElement.value = '';
  35. resolve(files);
  36. };
  37. inputElement.click();
  38. // #endif
  39. // #ifndef H5
  40. reject(new Error('此方法仅支持在H5平台调用'));
  41. // #endif
  42. });
  43. };