UploadAsset.vue 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. <script setup lang="ts">
  2. import { MaterialAPI } from '@/config/API.ts'
  3. import { useFileUpload } from '@/hooks/File/useFileUpload.ts'
  4. import { useMaterial } from '@/hooks/Material/useMaterial.ts'
  5. import router from '@/router'
  6. import type { ResponseInfo } from '@/types/axios.ts'
  7. import axiosInstance from '@/utils/axios/axiosInstance.ts'
  8. import type {
  9. GameData,
  10. GameSelectItem,
  11. ImgUploadRes,
  12. ResFileInfo,
  13. TagItem,
  14. UploadAssetForm,
  15. } from '@/views/Material/types/uploadFileType.ts'
  16. import type {
  17. FormInstance,
  18. FormRules,
  19. UploadFile,
  20. UploadFiles,
  21. UploadInstance,
  22. UploadRawFile,
  23. UploadRequestOptions,
  24. } from 'element-plus'
  25. import { ElMessageBox } from 'element-plus'
  26. import { nextTick, onMounted, type Reactive, reactive, ref, toRaw } from 'vue'
  27. import { VideoProcessor } from '@/utils/file/handleVideoFile.ts'
  28. import { ImageProcessor } from '@/utils/file/handleImgFile.ts'
  29. import TagSelect from '@/components/Material/TagSelect.vue'
  30. const { getAllTags } = useMaterial()
  31. const { isValidFile, handleFile } = useFileUpload()
  32. const { getGameInfo } = useMaterial()
  33. // 表单数据
  34. const uploadForm = reactive<UploadAssetForm>({
  35. name: '',
  36. tags: [],
  37. gid: '',
  38. pid: '',
  39. filePath: '',
  40. md5: '',
  41. isImg9: 1,
  42. resolution: {
  43. width: 0,
  44. height: 0,
  45. },
  46. headImgPath: '',
  47. videoType: 1,
  48. })
  49. // 表单规则
  50. const rules = reactive<FormRules<UploadAssetForm>>({
  51. name: [
  52. { required: true, message: '请输入创意名', trigger: 'blur' },
  53. { min: 1, max: 255, message: '3-5个字符', trigger: 'blur' },
  54. ],
  55. tags: [
  56. { required: true, message: '请选择标签', trigger: 'change' },
  57. { required: true, message: '请选择标签', trigger: 'blur' },
  58. ],
  59. isImg9: [
  60. { required: true, message: '请选择是否是九宫格', trigger: 'change' },
  61. ],
  62. gid: [{ required: true, message: '请选择游戏', trigger: 'change' }],
  63. filePath: [{ required: true, message: '请选择素材', trigger: 'change' }],
  64. })
  65. const gameSelect = reactive<GameSelectItem[]>([]) // 游戏级联选择框数据
  66. const uploadRef = ref<UploadInstance>()
  67. const fileFormRef = ref<FormInstance>()
  68. const tagInput = ref('') // 标签输入框数据
  69. const isVideo = ref(false) // 当前上传的时候是视频
  70. const limit = 1 // 限制上传文件数量
  71. const allTags: Array<TagItem> = [] // 所有标签
  72. const isUploading = ref(false)
  73. const videoDialogVisible = ref(false)
  74. const previewUrl = ref('')
  75. const previewVideoRef = ref<HTMLVideoElement>()
  76. const coverUrl = ref('') // 封面图片地址
  77. const coverFile = ref<File | null>(null) // 封面图片文件
  78. // 级联选择框属性配置
  79. const cascadePropsConfig = {
  80. expandTrigger: 'hover' as const,
  81. }
  82. /**
  83. * 选择游戏之后的处理
  84. * @param value 目前选择的值
  85. */
  86. const gameSelectChange = (value: string[]) => {
  87. uploadForm.pid = value[0]
  88. uploadForm.gid = value[1]
  89. }
  90. /**
  91. * 生成游戏级联选择框数据
  92. *
  93. * @param gameInfoList 游戏信息
  94. * @param gameSelect 级联选择框的值
  95. */
  96. const generateGameSelect = (
  97. gameInfoList: GameData,
  98. gameSelect: Reactive<GameSelectItem[]>,
  99. ) => {
  100. gameSelect.splice(0, gameSelect.length)
  101. for (let [k, v] of Object.entries(gameInfoList)) {
  102. const children = v.map(item => {
  103. return {
  104. value: item.gid,
  105. label: item.gameName,
  106. }
  107. })
  108. gameSelect.push({
  109. value: k,
  110. label: k === '' ? '默认' : k,
  111. children,
  112. })
  113. }
  114. }
  115. /**
  116. * 当文件列表发生变化时的处理事件
  117. *
  118. * @param file 选择的文件
  119. * @param fileList 文件列表
  120. */
  121. const handleFileChange = (file: UploadFile, fileList: UploadFiles) => {
  122. if (!file || !file.raw) {
  123. ElMessage.warning('请传入合法文件')
  124. return
  125. }
  126. // 不是合法文件直接返回不处理
  127. if (!isValidFile(file)) {
  128. fileList.splice(1)
  129. ElMessage.warning('上传文件超出限制或不是规定文件')
  130. return
  131. }
  132. // 统一处理文件上传
  133. const processUpload = async () => {
  134. handleFile(file, fileList, isVideo, uploadForm, previewUrl)
  135. nextTick(() => {
  136. fileFormRef.value?.validateField('filePath')
  137. })
  138. // 重置文件状态保证可重复上传
  139. fileList.forEach(f => (f.status = 'ready'))
  140. // 如果是视频的话,还需要生成封面
  141. if (isVideo.value) {
  142. nextTick(async () => {
  143. const videoProcessor = new VideoProcessor(previewUrl.value)
  144. const { width, height } = await videoProcessor.getVideoInfo()
  145. coverFile.value = await videoProcessor.generateCoverFile()
  146. // await uploadFormFile(file, true)
  147. // isUploading.value = false
  148. coverUrl.value = await videoProcessor.generateCover()
  149. uploadForm.resolution = {
  150. width,
  151. height,
  152. }
  153. })
  154. } else {
  155. const imgProcessor = new ImageProcessor(file.raw!)
  156. const { width, height } = await imgProcessor.getResolution()
  157. uploadForm.resolution = {
  158. width,
  159. height,
  160. }
  161. coverUrl.value = file.url!
  162. }
  163. }
  164. if (fileList.length > limit) {
  165. // 超限需要用户确认
  166. ElMessageBox.confirm('上传将覆盖前一个文件,是否继续上传?', {
  167. confirmButtonText: '继续上传',
  168. cancelButtonText: '取消',
  169. type: 'warning',
  170. })
  171. .then(() => {
  172. // 保留最新文件,删除旧文件(假设旧文件在数组开头)
  173. fileList.splice(0, 1)
  174. processUpload()
  175. })
  176. .catch(() => {
  177. // 取消时移除当前新增的文件
  178. const newFileIndex = fileList.findIndex(f => f.uid === file.uid)
  179. if (newFileIndex > -1) fileList.splice(newFileIndex, 1)
  180. })
  181. } else {
  182. // 未超限直接上传
  183. processUpload()
  184. }
  185. }
  186. /**
  187. * 处理表单提交
  188. *
  189. * 这个函数不处理表单的提交,只是作为触发器,完成表单验证的功能,然后将后续流程交给文件上传部分
  190. * @param formEl 表单对象
  191. */
  192. const submitAsset = async (formEl: FormInstance | undefined) => {
  193. if (isUploading.value) return
  194. if (!formEl) return
  195. // 表单验证
  196. const isValid = await formEl.validate()
  197. if (!isValid) {
  198. ElMessage.warning('请填写完整信息')
  199. return
  200. }
  201. // 交给文件上传的处理流程
  202. uploadRef.value?.submit()
  203. }
  204. /**
  205. * 上传单个文件,获得回显
  206. * @param file 上传的文件
  207. * @returns 回显信息,上传失败则是null
  208. */
  209. const uploadSingleFile = async (
  210. file: UploadRawFile | File,
  211. ): Promise<ResFileInfo | null> => {
  212. const formData = new FormData()
  213. formData.append('file', file)
  214. const result = (await axiosInstance.postForm(
  215. MaterialAPI.uploadAsset,
  216. formData,
  217. )) as ResFileInfo
  218. if (result.code !== 0) {
  219. ElMessage.error('上传素材失败')
  220. return null
  221. }
  222. return result
  223. }
  224. /**
  225. * 文件上传
  226. *
  227. * 表单提交需要先拿到文件上传成功后的回显,所以文件上传成功后才会执行表单的提交
  228. * @param options 上传文件信息
  229. */
  230. const uploadFormFile = async (options: UploadRequestOptions) => {
  231. if (!options || !options.file) {
  232. ElMessage.warning('请先上传文件')
  233. return
  234. }
  235. isUploading.value = true
  236. // 如果有封面图片,需要上传封面图片
  237. if (coverFile.value !== null) {
  238. const res = await uploadSingleFile(coverFile.value)
  239. if (!res) {
  240. isUploading.value = false
  241. return false
  242. }
  243. uploadForm.headImgPath = res.path
  244. }
  245. const file = options.file
  246. const res = await uploadSingleFile(file)
  247. if (!res) {
  248. isUploading.value = false
  249. return false
  250. }
  251. const { md5, path } = res
  252. uploadForm.md5 = md5
  253. uploadForm.filePath = path
  254. // 拿到回显后执行表单的提交流程
  255. await submitForm()
  256. }
  257. // 判断横版还是竖版,返回数字
  258. const getVideoType = (): 1 | 2 => {
  259. const { width, height } = uploadForm.resolution
  260. if (width > height) {
  261. return 1
  262. }
  263. return 2
  264. }
  265. const submitForm = async () => {
  266. const url = isVideo.value ? MaterialAPI.videoSubmit : MaterialAPI.imgSubmit
  267. const nFormData = JSON.parse(JSON.stringify(toRaw(uploadForm)))
  268. // 区分视频和图片,他们需要的字段不同
  269. if (isVideo.value) {
  270. nFormData.videoPath = nFormData.filePath
  271. nFormData.videoType = getVideoType()
  272. // 对于视频上传需要删除掉九宫格字段信息
  273. delete nFormData.isImg9
  274. } else {
  275. nFormData.imgPath = nFormData.filePath
  276. }
  277. // 移除不需要的filePath
  278. delete nFormData.filePath
  279. const res = (await axiosInstance.post(url, nFormData)) as ResponseInfo
  280. let result = res as ImgUploadRes
  281. if (isVideo.value) {
  282. result = res as ImgUploadRes
  283. }
  284. if (result.code !== 0) {
  285. ElMessage.error('上传素材失败')
  286. isUploading.value = false
  287. return
  288. }
  289. ElMessage.success('上传素材成功')
  290. isUploading.value = false
  291. // 重置表单
  292. uploadRef.value?.clearFiles()
  293. tagInput.value = ''
  294. fileFormRef.value?.resetFields()
  295. coverFile.value = null
  296. }
  297. /**
  298. * 返回上一页
  299. */
  300. const goBack = () => {
  301. router.back()
  302. }
  303. /**
  304. * 更新tag标签列表
  305. */
  306. const updateTags = async () => {
  307. const tags = await getAllTags()
  308. allTags.splice(0, allTags.length, ...tags)
  309. }
  310. /**
  311. * 更新游戏标签,并且重新生成游戏选择列表
  312. */
  313. const updateGameInfo = async () => {
  314. const info = await getGameInfo()
  315. if (info === null) {
  316. ElMessage.error('获取游戏信息失败')
  317. return
  318. }
  319. generateGameSelect(info, gameSelect)
  320. }
  321. /**
  322. * 处理预览
  323. */
  324. const handlePreview = () => {
  325. videoDialogVisible.value = true
  326. }
  327. onMounted(async () => {
  328. await updateTags()
  329. await updateGameInfo()
  330. })
  331. </script>
  332. <template>
  333. <div class="uploadAssetContainer">
  334. <el-page-header class="header" @back="goBack">
  335. <template #content>
  336. <span class="mr-3">上传素材</span>
  337. </template>
  338. </el-page-header>
  339. <div class="content">
  340. <p class="title">素材信息</p>
  341. <div class="formContainer">
  342. <el-form
  343. :rules="rules"
  344. :model="uploadForm"
  345. :label-position="'left'"
  346. ref="fileFormRef"
  347. label-width="auto"
  348. class="uploadForm"
  349. >
  350. <el-form-item label="创意名" prop="name">
  351. <el-input
  352. placeholder="请输入创意名"
  353. class="w220"
  354. v-model="uploadForm.name"
  355. />
  356. </el-form-item>
  357. <el-form-item v-if="!isVideo" label="是否是九宫格图片" prop="isImg9">
  358. <el-radio-group v-model="uploadForm.isImg9">
  359. <el-radio :value="1">是</el-radio>
  360. <el-radio :value="0">否</el-radio>
  361. </el-radio-group>
  362. </el-form-item>
  363. <el-form-item label="游戏" prop="gid">
  364. <el-cascader
  365. v-model="uploadForm.gid"
  366. :options="gameSelect"
  367. :props="cascadePropsConfig"
  368. @change="gameSelectChange"
  369. />
  370. </el-form-item>
  371. <el-form-item label="标签" prop="tags">
  372. <div class="tagContainer">
  373. <tag-select v-model:selected-tag="uploadForm.tags"></tag-select>
  374. </div>
  375. </el-form-item>
  376. <!-- :limit="limit"-->
  377. <el-form-item label="文件" prop="filePath">
  378. <div class="fileContainer">
  379. <el-upload
  380. class="uploadContainer"
  381. drag
  382. :auto-upload="false"
  383. list-type="picture"
  384. :on-change="handleFileChange"
  385. ref="uploadRef"
  386. :http-request="uploadFormFile"
  387. >
  388. <template #file="{ file }">
  389. <div class="fileInfo">
  390. <div class="fileIcon" @click="handlePreview">
  391. <el-image
  392. :src="coverUrl"
  393. class="fileListPreviewContent fileListPreviewImg"
  394. />
  395. <div class="fileListPreviewContent fileListPreviewMask">
  396. <el-icon>
  397. <zoom-in />
  398. </el-icon>
  399. </div>
  400. </div>
  401. <div>{{ file.name }}</div>
  402. </div>
  403. </template>
  404. <el-icon class="el-icon--upload">
  405. <upload-filled />
  406. </el-icon>
  407. <div class="el-upload__text">
  408. <p>将文件或文件夹拖到此处,或点击上传文件</p>
  409. <p class="upload-tips">1.仅支持图片和视频文件,单个上传</p>
  410. <p class="upload-tips">
  411. 2.支持图片格式:png、jpg、jpeg,不超过100MB;支持视频格式:mp4、avi,不超过100MB
  412. </p>
  413. <p class="upload-tips">
  414. 3.素材上传后需对尺寸、码率等进行分析,约1-3分钟后方可用于投放
  415. </p>
  416. </div>
  417. </el-upload>
  418. </div>
  419. </el-form-item>
  420. </el-form>
  421. <el-dialog
  422. v-model="videoDialogVisible"
  423. title="预览"
  424. class="previewDialog"
  425. >
  426. <div class="previewContainer">
  427. <video
  428. class="previewContent"
  429. v-if="isVideo"
  430. :src="previewUrl"
  431. width="400"
  432. height="400"
  433. controls
  434. ref="previewVideoRef"
  435. ></video>
  436. <img class="previewContent" v-else :src="previewUrl" alt="" />
  437. </div>
  438. </el-dialog>
  439. <div class="fileFooter">
  440. <el-button
  441. color="#197AFB"
  442. class="el-button-mini w120"
  443. @click="submitAsset(fileFormRef)"
  444. :loading="isUploading"
  445. >确定
  446. </el-button>
  447. </div>
  448. </div>
  449. </div>
  450. </div>
  451. </template>
  452. <style scoped>
  453. .uploadAssetContainer {
  454. width: 100%;
  455. }
  456. .header {
  457. width: 100%;
  458. height: 5vh;
  459. display: flex;
  460. background: #f8f9fc;
  461. align-items: center;
  462. padding-left: 30px;
  463. border-bottom: 1px solid #e8eaec;
  464. }
  465. .title {
  466. padding: 15px;
  467. font-size: 16px;
  468. font-weight: 700;
  469. color: #333;
  470. background: #f8f9fc;
  471. border-radius: 3px 3px 0 0;
  472. }
  473. .content {
  474. width: 90%;
  475. margin: 10px auto;
  476. }
  477. .formContainer {
  478. padding: 24px;
  479. background-color: #fff;
  480. }
  481. .tagContainer {
  482. display: flex;
  483. flex-direction: column;
  484. }
  485. .inputTag {
  486. margin-top: 15px;
  487. height: 50px;
  488. width: 800px;
  489. }
  490. .fileContainer {
  491. width: 800px;
  492. }
  493. .uploadContainer > .el-upload__text {
  494. color: #606266;
  495. font-size: 14px;
  496. text-align: center;
  497. }
  498. .upload-tips {
  499. color: #b6b7b7;
  500. }
  501. .fileInfo {
  502. display: flex;
  503. align-items: center;
  504. user-select: none;
  505. }
  506. .fileIcon {
  507. margin-right: 10px;
  508. position: relative;
  509. width: 100px;
  510. height: 100px;
  511. cursor: pointer;
  512. }
  513. .fileIcon:hover .fileListPreviewMask {
  514. visibility: visible;
  515. }
  516. .fileListPreviewContent {
  517. width: 100%;
  518. height: 100%;
  519. position: absolute;
  520. left: 0;
  521. top: 0;
  522. }
  523. .fileListPreviewMask {
  524. visibility: hidden;
  525. display: flex;
  526. align-items: center;
  527. justify-content: center;
  528. background-color: rgba(0, 0, 0, 0.6);
  529. color: white;
  530. font-size: 30px;
  531. }
  532. .previewDialog {
  533. width: 800px;
  534. height: 800px;
  535. }
  536. .previewContainer {
  537. width: 80%;
  538. height: 100%;
  539. margin: 0 auto;
  540. display: flex;
  541. justify-content: center;
  542. align-items: center;
  543. }
  544. </style>