choose-and-upload-image.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. import uploadFile from './upload-file';
  17. /**
  18. * 选择并上传图片到腾讯云COS(需要调用云函数签名,请先配置好云函数)
  19. * @async
  20. * @return {Promise<string>} 返回成功上传到COS上的文件名称
  21. */
  22. export default async function chooseAndUploadImage() {
  23. let [error, res] = await uni.chooseImage({
  24. count: 1,
  25. });
  26. if (error) {
  27. throw error;
  28. }
  29. // #ifdef H5
  30. if (!/^image/.test(res.tempFiles[0].type)) {
  31. throw new Error('文件类型错误');
  32. }
  33. // #endif
  34. uni.showLoading({
  35. mask: true,
  36. });
  37. try {
  38. let file = res.tempFilePaths[0];
  39. // #ifdef H5
  40. file = res.tempFiles[0];
  41. // #endif
  42. const key = await uploadFile(file);
  43. return key;
  44. } catch (error) {
  45. throw error;
  46. } finally {
  47. uni.hideLoading();
  48. }
  49. };