当前位置:   article > 正文

uniapp小程序上传文件

uniapp小程序上传文件

需求

小程序需要上传用户相册图片或拍摄的照片到后端服务器

uniapp官方处理小程序文件方法

选择文件方法:uni.chooseMedia

uni-app官网uni-app,uniCloud,serverless,uni.chooseVideo(OBJECT),chooseVideo HarmonyOS 兼容性,uni.chooseMedia(OBJECT),uni.saveVideoToPhotosAlbum(OBJECT),saveVideoToPhicon-default.png?t=N7T8https://uniapp.dcloud.net.cn/api/media/video.html#choosemedia

上传文件方法:uni.uploadFile

uni.uploadFile(OBJECT) | uni-app官网uni-app,uniCloud,serverless,uni.uploadFile(OBJECT),uploadFile HarmonyOS 兼容性,参数 HarmonyOS 兼容性,返回值 HarmonyOS 兼容性,UploadTask 的方法,abort(),onProgressUpdateicon-default.png?t=N7T8https://uniapp.dcloud.net.cn/api/request/network-file.html#uploadfile

前端代码

前端项目为vue3类型的uniapp小程序项目

这里封装一个简单的插件来处理图片的选择和上传

  1. <template>
  2. <view class="flex align-start flex-wrap padding-bottom">
  3. <view class="flex flex-direction align-center justify-between margin-left-lg margin-top"
  4. v-for="(item,index) in innerFileList" :key="index">
  5. <image class="cu-avatar xl radius" mode="scaleToFill" :src="item.fileUrl" @tap="previewImg(item)"></image>
  6. <text class='text-second' @tap="handleDelete(item)">删除图片</text>
  7. </view>
  8. <view class="cu-avatar xl radius margin-left-lg margin-top" @tap="handleChoose">
  9. <text class="cuIcon-pic"></text>
  10. </view>
  11. </view>
  12. </template>
  13. <script setup>
  14. import {
  15. ref,
  16. computed,
  17. reactive,
  18. onMounted,
  19. watch
  20. } from 'vue'
  21. import {
  22. useStore
  23. } from 'vuex'
  24. import {
  25. toastError,
  26. toastMessage
  27. } from '@/util/common.js'
  28. const props = defineProps({
  29. fileList: Array,
  30. fileUse: Number,
  31. limit: {
  32. type: Number,
  33. default: 5
  34. }
  35. })
  36. const store = useStore()
  37. const emits = defineEmits(['updateFile'])
  38. const token = computed(() => store.state.token)
  39. const innerFileList = ref([])
  40. onMounted(() => {
  41. getFileList()
  42. })
  43. watch(() => props.fileList, (n, o) => {
  44. if (!n || !n.length) {
  45. innerFileList.value = []
  46. } else if (!innerFileList.value.length) {
  47. getFileList()
  48. } else {
  49. if (n.length !== innerFileList.value.length) {
  50. getFileList()
  51. }
  52. }
  53. })
  54. const getFileList = () => {
  55. innerFileList.value = []
  56. if (props.fileList && props.fileList.length) {
  57. for (let item of props.fileList) {
  58. item.fileUrl = getFileUrl(item.fileToken)
  59. }
  60. innerFileList.value = props.fileList
  61. }
  62. }
  63. const {
  64. getFileUrl
  65. } = useGetFileUrl()
  66. // 删除文件
  67. const handleDelete = item => {
  68. uni.showModal({
  69. title: '确定删除吗?',
  70. content: '确定删除该图片吗',
  71. success: res => {
  72. if (res.confirm) {
  73. let index = innerFileList.value.findIndex(x => x.fileUrl === item.fileUrl)
  74. innerFileList.value.splice(index, 1)
  75. }
  76. }
  77. })
  78. }
  79. // 选择文件
  80. const handleChoose = () => {
  81. if (innerFileList.value.length >= props.limit) {
  82. toastError('不能超过' + props.limit + '张')
  83. return
  84. }
  85. // #ifdef MP-WEIXIN
  86. uni.chooseMedia({
  87. count: 1,
  88. mediaType: ['image'],
  89. fail: error => {
  90. console.log('图片选择失败', error)
  91. },
  92. success: res => {
  93. let file = res.tempFiles[0]
  94. innerFileList.value.push({
  95. id: 0,
  96. fileUrl: file.tempFilePath
  97. })
  98. if (!file) return
  99. handleUpload(file.tempFilePath, '手机图片')
  100. }
  101. })
  102. // #endif
  103. // #ifdef APP
  104. uni.chooseImage({
  105. count: 1,
  106. fail: error => {
  107. console.log('图片选择失败', error)
  108. },
  109. success: res => {
  110. let filePath = res.tempFilePaths[0]
  111. innerFileList.value.push({
  112. id: 0,
  113. fileUrl: filePath
  114. })
  115. if (!filePath) return
  116. handleUpload(filePath, '手机图片')
  117. }
  118. })
  119. // #endif
  120. }
  121. const handleUpload = (filePath, name) => {
  122. let accessToken = 'Bearer ' + token.value
  123. let uploadUrl = '我的服务器url'
  124. uni.uploadFile({
  125. url: uploadUrl,
  126. filePath: filePath,
  127. name: name,
  128. header: {
  129. Authorization: accessToken,
  130. },
  131. fail: error => {
  132. console.log('图片上传失败', error)
  133. toastError('图片上传失败')
  134. },
  135. success: uploadRes => {
  136. console.log('图片上传成功', uploadRes)
  137. if (uploadRes.statusCode === 200) {
  138. let data = JSON.parse(uploadRes.data)
  139. if (data.data) {
  140. let item = innerFileList.value[innerFileList.value.length - 1]
  141. item.fileId = data.data.picId
  142. item.fileToken = data.data.picToken
  143. item.fileUse = props.fileUse
  144. emits('updateFile', innerFileList.value)
  145. }
  146. }
  147. }
  148. })
  149. }
  150. // 预览
  151. const previewImg = item => {
  152. let urls = [item.fileUrl]
  153. uni.previewImage({
  154. urls: urls
  155. })
  156. }
  157. </script>
  158. <style>
  159. </style>

后端代码

后端项目为asp.net6的webapi项目

注意入参为IFormCollection formCollection  和web项目的IFormFile file入参有所区别

  1. [HttpPost("upload_app_sales_order_cert")]
  2. [Authorize]
  3. public async Task<CommonResponse<UploadFileRes>> UploadSalesOrderCertApp(IFormCollection formCollection)
  4. {
  5. var user = GetUser();
  6. FormFileCollection formFiles = (FormFileCollection)formCollection.Files;
  7. var file = formFiles[0];
  8. //这里换成自己的业务逻辑
  9. var res = await _uploadDataService.UploadFileAsync(file, user.UserId, user.DealerId, FileUse.销售单凭证);
  10. return new CommonResponse<UploadFileRes>(res);
  11. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/802520
推荐阅读
相关标签
  

闽ICP备14008679号