upload-file.vue 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <template>
  2. <view>
  3. <page-head :title="title"></page-head>
  4. <view class="uni-padding-wrap uni-common-mt">
  5. <view class="demo">
  6. <block v-if="imageSrc">
  7. <image :src="imageSrc" class="image" mode="widthFix"></image>
  8. </block>
  9. <block v-else>
  10. <view class="uni-hello-addfile" @click="chooseImage">+ 选择图片</view>
  11. </block>
  12. </view>
  13. </view>
  14. </view>
  15. </template>
  16. <script>
  17. export default {
  18. data() {
  19. return {
  20. title: 'uploadFile',
  21. imageSrc: ''
  22. }
  23. },
  24. onUnload() {
  25. this.imageSrc = '';
  26. },
  27. methods: {
  28. chooseImage: function() {
  29. uni.chooseImage({
  30. count: 1,
  31. sizeType: ['compressed'],
  32. sourceType: ['album'],
  33. success: (res) => {
  34. console.log('chooseImage success, temp path is', res.tempFilePaths[0])
  35. var imageSrc = res.tempFilePaths[0]
  36. uni.uploadFile({
  37. url: 'https://unidemo.dcloud.net.cn/upload',
  38. filePath: imageSrc,
  39. fileType: 'image',
  40. name: 'data',
  41. success: (res) => {
  42. console.log('uploadImage success, res is:', res)
  43. uni.showToast({
  44. title: '上传成功',
  45. icon: 'success',
  46. duration: 1000
  47. })
  48. this.imageSrc = imageSrc
  49. },
  50. fail: (err) => {
  51. console.log('uploadImage fail', err);
  52. uni.showModal({
  53. content: err.errMsg,
  54. showCancel: false
  55. });
  56. }
  57. });
  58. },
  59. fail: (err) => {
  60. console.log('chooseImage fail', err)
  61. // #ifdef MP
  62. uni.getSetting({
  63. success: (res) => {
  64. let authStatus = res.authSetting['scope.album'];
  65. if (!authStatus) {
  66. uni.showModal({
  67. title: '授权失败',
  68. content: 'Hello uni-app需要从您的相册获取图片,请在设置界面打开相关权限',
  69. success: (res) => {
  70. if (res.confirm) {
  71. uni.openSetting()
  72. }
  73. }
  74. })
  75. }
  76. }
  77. })
  78. // #endif
  79. }
  80. })
  81. }
  82. }
  83. }
  84. </script>
  85. <style>
  86. .image {
  87. width: 100%;
  88. }
  89. .demo {
  90. background: #FFF;
  91. padding: 50rpx;
  92. }
  93. </style>