file-upload.vue 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <template>
  2. <el-upload
  3. class="upload-demo"
  4. action="/files/cms/attachment/upload"
  5. :limit="limit"
  6. v-once
  7. :file-list="[...this.fileList]"
  8. :on-preview="handlePreview"
  9. :before-remove="beforeRemove"
  10. :on-exceed="handleExceed"
  11. :before-upload="beforeUpload"
  12. :on-success="handleSuccess"
  13. >
  14. <el-button size="mini" type="primary">点击上传</el-button>
  15. <div slot="tip" class="el-upload__tip">文件大小不能超过5MB</div>
  16. </el-upload>
  17. </template>
  18. <script>
  19. export default {
  20. name: 'file-upload',
  21. model: {
  22. prop: 'value',
  23. event: 'change', // 默认为input时间,此处改为change
  24. },
  25. props: {
  26. value: { type: Array, required: false, default: () => [] },
  27. limit: { type: Number, required: false, default: 3 },
  28. },
  29. data() {
  30. return {
  31. fileList: [...this.value],
  32. };
  33. },
  34. methods: {
  35. handlePreview(file) {
  36. console.log(file);
  37. },
  38. handleExceed(files, fileList) {
  39. this.$message.warning(`当前限制选择 ${this.limit} 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
  40. },
  41. handleSuccess(res, file) {
  42. console.log({ res, file });
  43. if (res.errcode !== 0) {
  44. this.$notify.error({
  45. title: '错误',
  46. message: '文件上传失败',
  47. });
  48. return;
  49. }
  50. this.fileList.push({ name: file.name, uri: res.uri, uid: file.uid });
  51. this.$emit('change', this.fileList);
  52. this.$message({ type: 'success', message: '文件上传成功' });
  53. return true;
  54. },
  55. beforeRemove(file, fileList) {
  56. const isExisted = this.fileList.some(p => p.uid === file.uid);
  57. if (!isExisted) {
  58. return true;
  59. }
  60. return this.$confirm(`确定移除 ${file.name}?`).then(() => {
  61. const idx = this.fileList.findIndex(p => p.name === file.name);
  62. if (idx != -1) {
  63. this.fileList.splice(idx, 1);
  64. this.$emit('change', this.fileList);
  65. }
  66. });
  67. },
  68. beforeUpload(file) {
  69. // TODO: 检查文件是否已上传
  70. const isExisted = this.fileList.some(p => p.name === file.name);
  71. if (isExisted) {
  72. console.warn(`文件${file.name}已存在,不能重复上传!`);
  73. return false;
  74. }
  75. // TODO: 检查文件大小
  76. const isLt5M = file.size / 1024 / 1024 < 5;
  77. if (!isLt5M) {
  78. //this.$message.error("上传确认函图片大小不能超过 2MB!");
  79. this.$message({ type: 'error', message: '上传文件大小不能超过 5MB!', duration: 3000 });
  80. return false;
  81. }
  82. return true;
  83. },
  84. handleChange(file, fileList) {
  85. const newList = fileList.map(p => ({ name: p.name, uri: p.uri }));
  86. this.$emit('change', newList);
  87. },
  88. },
  89. };
  90. </script>