index.vue 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. <template>
  2. <div class="component-upload-image">
  3. <el-upload
  4. multiple
  5. :disabled="disabled"
  6. :http-request="customUpload"
  7. list-type="picture-card"
  8. :before-upload="handleBeforeUpload"
  9. :limit="limit"
  10. :on-error="handleUploadError"
  11. :on-exceed="handleExceed"
  12. ref="imageUpload"
  13. :before-remove="handleDelete"
  14. :show-file-list="true"
  15. :file-list="fileList"
  16. :on-preview="handlePictureCardPreview"
  17. :class="{ hide: fileList.length >= limit }"
  18. >
  19. <el-icon class="avatar-uploader-icon"><plus /></el-icon>
  20. </el-upload>
  21. <!-- 上传提示 -->
  22. <div class="el-upload__tip" v-if="showTip && !disabled">
  23. 请上传
  24. <template v-if="fileSize">
  25. 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
  26. </template>
  27. <template v-if="fileType">
  28. 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b>
  29. </template>
  30. 的文件
  31. </div>
  32. <el-dialog
  33. v-model="dialogVisible"
  34. title="预览"
  35. width="800px"
  36. append-to-body
  37. >
  38. <img
  39. :src="dialogImageUrl"
  40. style="display: block; max-width: 100%; margin: 0 auto"
  41. />
  42. </el-dialog>
  43. </div>
  44. </template>
  45. <script setup>
  46. import { getToken } from "@/utils/auth"
  47. import { isExternal } from "@/utils/validate"
  48. import Sortable from 'sortablejs'
  49. import request from "@/utils/request"
  50. const props = defineProps({
  51. modelValue: [String, Object, Array],
  52. // 上传接口地址
  53. action: {
  54. type: String,
  55. default: "/common/upload"
  56. },
  57. // 上传携带的参数
  58. data: {
  59. type: Object
  60. },
  61. // 图片数量限制
  62. limit: {
  63. type: Number,
  64. default: 5
  65. },
  66. // 大小限制(MB)
  67. fileSize: {
  68. type: Number,
  69. default: 5
  70. },
  71. // 文件类型, 例如['png', 'jpg', 'jpeg']
  72. fileType: {
  73. type: Array,
  74. default: () => ["png", "jpg", "jpeg"]
  75. },
  76. // 是否显示提示
  77. isShowTip: {
  78. type: Boolean,
  79. default: true
  80. },
  81. // 禁用组件(仅查看图片)
  82. disabled: {
  83. type: Boolean,
  84. default: false
  85. },
  86. // 拖动排序
  87. drag: {
  88. type: Boolean,
  89. default: true
  90. }
  91. })
  92. const { proxy } = getCurrentInstance()
  93. const emit = defineEmits()
  94. const number = ref(0)
  95. const uploadList = ref([])
  96. const dialogImageUrl = ref("")
  97. const dialogVisible = ref(false)
  98. const baseUrl = import.meta.env.VITE_APP_BASE_API
  99. const uploadImgUrl = ref(import.meta.env.VITE_APP_BASE_API + props.action) // 上传的图片服务器地址
  100. const headers = ref({ Authorization: "Bearer " + getToken() })
  101. const fileList = ref([])
  102. const showTip = computed(
  103. () => props.isShowTip && (props.fileType || props.fileSize)
  104. )
  105. watch(() => props.modelValue, val => {
  106. if (val) {
  107. // 首先将值转为数组
  108. const list = Array.isArray(val) ? val : props.modelValue.split(",")
  109. // 然后将数组转为对象数组
  110. fileList.value = list.map(item => {
  111. if (typeof item === "string") {
  112. if (item.indexOf(baseUrl) === -1 && !isExternal(item)) {
  113. item = { name: baseUrl + item, url: baseUrl + item }
  114. } else {
  115. item = { name: item, url: item }
  116. }
  117. }
  118. return item
  119. })
  120. } else {
  121. fileList.value = []
  122. return []
  123. }
  124. },{ deep: true, immediate: true })
  125. // 上传前loading加载
  126. function handleBeforeUpload(file) {
  127. let isImg = false
  128. if (props.fileType.length) {
  129. let fileExtension = ""
  130. if (file.name.lastIndexOf(".") > -1) {
  131. fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1)
  132. }
  133. isImg = props.fileType.some(type => {
  134. if (file.type.indexOf(type) > -1) return true
  135. if (fileExtension && fileExtension.indexOf(type) > -1) return true
  136. return false
  137. })
  138. } else {
  139. isImg = file.type.indexOf("image") > -1
  140. }
  141. if (!isImg) {
  142. proxy.$modal.msgError(`文件格式不正确,请上传${props.fileType.join("/")}图片格式文件!`)
  143. return false
  144. }
  145. if (file.name.includes(',')) {
  146. proxy.$modal.msgError('文件名不正确,不能包含英文逗号!')
  147. return false
  148. }
  149. if (props.fileSize) {
  150. const isLt = file.size / 1024 / 1024 < props.fileSize
  151. if (!isLt) {
  152. proxy.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`)
  153. return false
  154. }
  155. }
  156. proxy.$modal.loading("正在上传图片,请稍候...")
  157. number.value++
  158. }
  159. // 文件个数超出
  160. function handleExceed() {
  161. proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`)
  162. }
  163. // 自定义上传方法 - 通过后端获取签名后上传到OSS
  164. async function customUpload(options) {
  165. const file = options.file
  166. try {
  167. // 1. 从后端获取OSS签名
  168. const signatureResponse = await request({
  169. url: '/common/oss/signature',
  170. method: 'get',
  171. params: {
  172. dir: 'dept/logo/'
  173. }
  174. })
  175. if (signatureResponse.code !== 200 || !signatureResponse.data) {
  176. throw new Error(signatureResponse.msg || '获取OSS签名失败')
  177. }
  178. const signature = signatureResponse.data
  179. // 2. 生成文件路径
  180. const filePath = generateFilePath(file, signature.dir)
  181. // 3. 构建FormData,使用PostObject方式上传
  182. const formData = new FormData()
  183. formData.append('key', filePath)
  184. formData.append('policy', signature.policy)
  185. formData.append('OSSAccessKeyId', signature.accessKeyId)
  186. formData.append('signature', signature.signature)
  187. formData.append('file', file)
  188. // 4. 上传到OSS
  189. const response = await fetch(signature.host, {
  190. method: 'POST',
  191. body: formData
  192. })
  193. if (response.ok || response.status === 204) {
  194. // 上传成功,返回OSS URL
  195. const ossUrl = `${signature.host}/${filePath}`
  196. handleUploadSuccess({
  197. code: 200,
  198. fileName: filePath,
  199. url: ossUrl
  200. }, file)
  201. } else {
  202. const errorText = await response.text()
  203. throw new Error(`上传失败: ${response.status} ${errorText}`)
  204. }
  205. } catch (error) {
  206. console.error('OSS上传失败:', error)
  207. proxy.$modal.closeLoading()
  208. proxy.$modal.msgError('上传图片失败: ' + (error.message || '未知错误'))
  209. number.value--
  210. if (proxy.$refs.imageUpload) {
  211. proxy.$refs.imageUpload.handleRemove(file)
  212. }
  213. }
  214. }
  215. // 生成文件路径
  216. function generateFilePath(file, dir) {
  217. const date = new Date()
  218. const year = date.getFullYear()
  219. const month = String(date.getMonth() + 1).padStart(2, '0')
  220. const day = String(date.getDate()).padStart(2, '0')
  221. const timestamp = Date.now()
  222. const random = Math.random().toString(36).substring(2, 15)
  223. const ext = file.name.substring(file.name.lastIndexOf('.'))
  224. return `${dir}${year}/${month}/${day}/${timestamp}_${random}${ext}`
  225. }
  226. // 上传成功回调
  227. function handleUploadSuccess(res, file) {
  228. if (res.code === 200) {
  229. // 使用OSS的完整URL
  230. uploadList.value.push({ name: res.fileName, url: res.url || res.fileName })
  231. uploadedSuccessfully()
  232. } else {
  233. number.value--
  234. proxy.$modal.closeLoading()
  235. proxy.$modal.msgError(res.msg || '上传失败')
  236. if (proxy.$refs.imageUpload) {
  237. proxy.$refs.imageUpload.handleRemove(file)
  238. }
  239. uploadedSuccessfully()
  240. }
  241. }
  242. // 删除图片
  243. function handleDelete(file) {
  244. const findex = fileList.value.map(f => f.name).indexOf(file.name)
  245. if (findex > -1 && uploadList.value.length === number.value) {
  246. fileList.value.splice(findex, 1)
  247. emit("update:modelValue", listToString(fileList.value))
  248. return false
  249. }
  250. }
  251. // 上传结束处理
  252. function uploadedSuccessfully() {
  253. if (number.value > 0 && uploadList.value.length === number.value) {
  254. fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value)
  255. uploadList.value = []
  256. number.value = 0
  257. emit("update:modelValue", listToString(fileList.value))
  258. proxy.$modal.closeLoading()
  259. }
  260. }
  261. // 上传失败
  262. function handleUploadError() {
  263. proxy.$modal.msgError("上传图片失败")
  264. proxy.$modal.closeLoading()
  265. }
  266. // 预览
  267. function handlePictureCardPreview(file) {
  268. dialogImageUrl.value = file.url
  269. dialogVisible.value = true
  270. }
  271. // 对象转成指定字符串分隔
  272. function listToString(list, separator) {
  273. let strs = ""
  274. separator = separator || ","
  275. for (let i in list) {
  276. if (undefined !== list[i].url && list[i].url.indexOf("blob:") !== 0) {
  277. // 如果是OSS URL,直接使用;否则去掉baseUrl
  278. const url = list[i].url
  279. if (url.startsWith('http://') || url.startsWith('https://')) {
  280. strs += url + separator
  281. } else {
  282. strs += url.replace(baseUrl, "") + separator
  283. }
  284. }
  285. }
  286. return strs != "" ? strs.substr(0, strs.length - 1) : ""
  287. }
  288. // 初始化拖拽排序
  289. onMounted(() => {
  290. if (props.drag && !props.disabled) {
  291. nextTick(() => {
  292. const element = proxy.$refs.imageUpload?.$el?.querySelector('.el-upload-list')
  293. Sortable.create(element, {
  294. onEnd: (evt) => {
  295. const movedItem = fileList.value.splice(evt.oldIndex, 1)[0]
  296. fileList.value.splice(evt.newIndex, 0, movedItem)
  297. emit('update:modelValue', listToString(fileList.value))
  298. }
  299. })
  300. })
  301. }
  302. })
  303. </script>
  304. <style scoped lang="scss">
  305. // .el-upload--picture-card 控制加号部分
  306. :deep(.hide .el-upload--picture-card) {
  307. display: none;
  308. }
  309. :deep(.el-upload.el-upload--picture-card.is-disabled) {
  310. display: none !important;
  311. }
  312. </style>