uploadFile.vue 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. <style>
  2. </style>
  3. <style lang="scss" scoped>
  4. </style>
  5. <template>
  6. <div class="upload-file">
  7. <a-upload name="file" :multiple="multiple" list-type="picture-card" class="avatar-uploader"
  8. action="https://media-1301855440.cos.ap-chongqing.myqcloud.com/" :before-upload="beforeUpload"
  9. @change="handleChange" :accept="uploadType+'/'+(uploadType=='image'?'jpeg,image/jpg':'mp4')" :file-list="fileList"
  10. :remove="removeFile" @preview="handlePreview" :disabled="loadingElse||disabled">
  11. <div v-if="uploadType=='image'?fileList.length < fileCount:fileList.length<1">
  12. <a-progress v-if='loadingElse' :percent="percent" :show-info="false" />
  13. <div class="ant-upload-text">
  14. 点击上传
  15. </div>
  16. </div>
  17. </a-upload>
  18. <div style="color:red">{{uploadType=='image'?'请上传jpg格式的图片,并且大小在2m之内':'请上传mp4格式,大小在100m之内'}}</div>
  19. <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
  20. <img alt="example" style="width: 100%" :src="previewImage" v-if="uploadType=='image'" />
  21. <video :src="previewImage" v-else style="width: 100%" controls="controls">您的浏览器不支持 video 标签。</video>
  22. </a-modal>
  23. </div>
  24. </template>
  25. <script>
  26. import {
  27. stopOtherVideo,
  28. closeAllVideoFun
  29. } from '@/utils/videoControl' // 停止除当前外的其他视频播放,及停止所有视频播放的方法
  30. import {
  31. mapGetters
  32. } from 'vuex'
  33. import moment from 'moment'
  34. import BMF from 'browser-md5-file'
  35. import qs from 'qs'
  36. var COS = require('cos-js-sdk-v5');
  37. var cos = new COS({
  38. SecretId: 'AKIDE6IpMi8fJQRCg1iuWzFajjRs43kbbets',
  39. SecretKey: 'tXzuwMfplTTK3c9GFUyETilasvQfePu9',
  40. });
  41. var i = 0
  42. const oneKB = 1024
  43. function getBase64(file) {
  44. return new Promise((resolve, reject) => {
  45. const reader = new FileReader();
  46. reader.readAsDataURL(file);
  47. reader.onload = () => resolve(reader.result);
  48. reader.onerror = error => reject(error);
  49. });
  50. }
  51. export default {
  52. name: 'upload-file',
  53. components: {},
  54. props: {
  55. uploadType: { //上传类型 值为 image/video,同时目录名称也是这样
  56. type: String,
  57. default () {
  58. return 'image'
  59. }
  60. },
  61. multiple: { // true 可以批量上传 false 不可以
  62. type: Boolean,
  63. default () {
  64. return true
  65. }
  66. },
  67. fileCount: { //最大上传数量
  68. type: Number,
  69. default () {
  70. return 10
  71. }
  72. },
  73. checkFile: { //返回promise方法,判读文件是否上传过,进行上传拦截
  74. type: Function,
  75. default (file) {
  76. return Promise.resolve()
  77. }
  78. },
  79. disabled: {
  80. type: Boolean,
  81. default () {
  82. return false
  83. }
  84. },
  85. value: {
  86. type: [String, Array],
  87. required: true
  88. },
  89. size: {
  90. type: Number,
  91. default () {
  92. if (this.uploadType == 'image') {
  93. return 2048
  94. } else {
  95. return 102400
  96. }
  97. }
  98. },
  99. onOversize: {
  100. type: Function,
  101. default () {
  102. alert(`请选择${this.size}KB内的文件!`)
  103. }
  104. },
  105. },
  106. data() {
  107. return {
  108. fileList: [],
  109. loadingElse: false,
  110. imageUrl: '',
  111. percent: 0,
  112. previewVisible: false,
  113. previewImage: '',
  114. }
  115. },
  116. filters: {},
  117. computed: {},
  118. mounted() {
  119. },
  120. watch: {
  121. // fileListAll
  122. value: {
  123. immediate: true,
  124. handler(n, o) {
  125. if (this.fileList.length == 0) {
  126. if (typeof n == 'object') {
  127. this.fileList = n.map((item, index) => {
  128. return {
  129. uid: index + 1,
  130. name: index + 1,
  131. status: 'done',
  132. url: item,
  133. }
  134. })
  135. } else {
  136. if (n == '') {
  137. this.fileList = []
  138. } else {
  139. this.fileList = [{
  140. uid: 1,
  141. name: 1,
  142. status: 'done',
  143. url: n,
  144. }]
  145. }
  146. }
  147. } else {
  148. if (n.length == 0 || n == '') {
  149. this.clearAll()
  150. }
  151. }
  152. },
  153. deep: true
  154. }
  155. },
  156. methods: {
  157. handleCancel() {
  158. closeAllVideoFun()
  159. this.previewVisible = false;
  160. },
  161. handleChange(info) {
  162. if (info.file.status === 'uploading') {
  163. this.loading = true;
  164. return;
  165. }
  166. if (info.file.status === 'done') {
  167. // Get this url from response in real world.
  168. getBase64(info.file.originFileObj, imageUrl => {
  169. this.imageUrl = imageUrl;
  170. this.loading = false;
  171. });
  172. }
  173. },
  174. removeFile(file) {
  175. console.log(file)
  176. var index = this.fileList.findIndex(v => v.uid === file.uid)
  177. this.fileList.splice(index, 1)
  178. this.$emit('removeUpload', file)
  179. },
  180. async handlePreview(file) {
  181. if (!file.url && !file.preview) {
  182. file.preview = await getBase64(file.originFileObj);
  183. }
  184. this.previewImage = file.url || file.preview;
  185. this.previewVisible = true;
  186. },
  187. beforeUpload(file) {
  188. this.percent = 0
  189. this.loadingElse = true
  190. const fileOvesize = (file.size > this.size * oneKB)
  191. console.log(fileOvesize)
  192. if (fileOvesize) {
  193. this.onOversize()
  194. this.loadingElse = false
  195. return
  196. } else {
  197. this.checkFile(file).then(res => {
  198. this.cosUpload(file)
  199. }).catch(() => {
  200. this.loadingElse = false
  201. })
  202. return new Promise(function (resolve, reject) {
  203. reject()
  204. })
  205. }
  206. },
  207. clearAll() {
  208. this.fileList = []
  209. },
  210. cosUpload(file) {
  211. var that = this
  212. let date = new Date()
  213. let y = date.getFullYear()
  214. let MM = date.getMonth() + 1
  215. MM = MM < 10 ? '0' + MM : MM
  216. let d = date.getDate()
  217. d = d < 10 ? '0' + d : d
  218. var timeElse = new Date().getTime()
  219. var arr = file.name.split('.')
  220. var str = ''
  221. for (let i = 0; i < arr.length; i++) {
  222. if (i == arr.length - 1) {} else {
  223. if (i == arr.length - 2) {
  224. str += arr[i]
  225. } else {
  226. str += (arr[i] + '.')
  227. }
  228. }
  229. }
  230. console.log(str + '-' + timeElse + '.' + arr[arr.length - 1])
  231. cos.putObject({
  232. Bucket: 'media-1301855440',
  233. /* 必须 */
  234. Region: 'ap-thirdpart',
  235. /* 存储桶所在地域,必须字段 */
  236. Key: that.uploadType + '/' + y + '-' + MM + '-' + d + '/' + str + '-' + timeElse + '.' + arr[arr
  237. .length - 1],
  238. /* 必须 */
  239. StorageClass: 'STANDARD',
  240. Body: file, // 上传文件对象
  241. onProgress: function (progressData) { //进度条方法
  242. that.percent = (progressData.percent * 100)
  243. },
  244. onTaskReady: function (tid) {
  245. // console.log('onTaskReady', tid);
  246. },
  247. onTaskStart: function (info) { //开始上传
  248. // console.log('onTaskStart', info);
  249. },
  250. }, function (err, data) {
  251. if (err) {
  252. that.loadingElse = false
  253. that.$message.error('上传失败!!!' + err)
  254. return;
  255. }
  256. // alert('成功')
  257. that.loadingElse = false
  258. if (that.fileList.length < that.fileCount) {
  259. that.fileList.push({
  260. uid: file.name,
  261. name: file.name,
  262. status: 'done',
  263. url: '//' + data.Location,
  264. })
  265. // that.$emit('overUpload', that.fileList.map(item => {
  266. // return item.url
  267. // }))
  268. that.$emit('overUpload', that.fileList)
  269. if (that.multiple) {
  270. that.$emit('update:value', that.fileList.map(item => {
  271. return item.url
  272. }))
  273. } else {
  274. that.$emit('update:value', that.fileList.map(item => {
  275. return item.url
  276. })[0])
  277. }
  278. } else {
  279. that.$message.error('上传已达上限' + that.fileCount + '张')
  280. }
  281. });
  282. }
  283. }
  284. }
  285. </script>
  286. <style scoped>
  287. @import '~@assets/less/common.less';
  288. </style>