Upload上传 - 图1

Upload 上传

文件选择上传和拖拽上传控件。

何时使用

上传是将信息(网页、文字、图片、视频等)通过网页或者上传工具发布到远程服务器上的过程。

  • 当需要上传一个或一些文件时。
  • 当需要展现上传的进度时。
  • 当需要使用拖拽交互时。

代码演示

Upload上传 - 图2Click to Upload

点击上传

经典款式,用户点击按钮弹出文件选择框。

  1. <template>
  2. <a-upload
  3. v-model:file-list="fileList"
  4. name="file"
  5. :multiple="true"
  6. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  7. :headers="headers"
  8. @change="handleChange"
  9. >
  10. <a-button>
  11. <upload-outlined></upload-outlined>
  12. Click to Upload
  13. </a-button>
  14. </a-upload>
  15. </template>
  16. <script lang="ts">
  17. import { message } from 'ant-design-vue';
  18. import { UploadOutlined } from '@ant-design/icons-vue';
  19. import { defineComponent, ref } from 'vue';
  20. interface FileItem {
  21. uid: string;
  22. name?: string;
  23. status?: string;
  24. response?: string;
  25. url?: string;
  26. }
  27. interface FileInfo {
  28. file: FileItem;
  29. fileList: FileItem[];
  30. }
  31. export default defineComponent({
  32. components: {
  33. UploadOutlined,
  34. },
  35. setup() {
  36. const handleChange = (info: FileInfo) => {
  37. if (info.file.status !== 'uploading') {
  38. console.log(info.file, info.fileList);
  39. }
  40. if (info.file.status === 'done') {
  41. message.success(`${info.file.name} file uploaded successfully`);
  42. } else if (info.file.status === 'error') {
  43. message.error(`${info.file.name} file upload failed.`);
  44. }
  45. };
  46. const fileList = ref([]);
  47. return {
  48. fileList,
  49. headers: {
  50. authorization: 'authorization-text',
  51. },
  52. handleChange,
  53. };
  54. },
  55. });
  56. </script>

Upload上传 - 图3Upload

Upload上传 - 图4xxx.pngUpload上传 - 图5

Upload上传 - 图6yyy.pngUpload上传 - 图7

Upload上传 - 图8zzz.pngUpload上传 - 图9

已上传的文件列表

使用 defaultFileList 设置已上传的内容。

  1. <template>
  2. <a-upload action="https://www.mocky.io/v2/5cc8019d300000980a055e76" v-model:file-list="fileList">
  3. <a-button>
  4. <upload-outlined></upload-outlined>
  5. Upload
  6. </a-button>
  7. </a-upload>
  8. </template>
  9. <script lang="ts">
  10. import { UploadOutlined } from '@ant-design/icons-vue';
  11. import { defineComponent, ref } from 'vue';
  12. interface FileItem {
  13. uid: string;
  14. name?: string;
  15. status?: string;
  16. response?: string;
  17. url?: string;
  18. }
  19. interface FileInfo {
  20. file: FileItem;
  21. fileList: FileItem[];
  22. }
  23. export default defineComponent({
  24. components: {
  25. UploadOutlined,
  26. },
  27. setup() {
  28. const fileList = ref<FileItem[]>([
  29. {
  30. uid: '1',
  31. name: 'xxx.png',
  32. status: 'done',
  33. response: 'Server Error 500', // custom error message to show
  34. url: 'http://www.baidu.com/xxx.png',
  35. },
  36. {
  37. uid: '2',
  38. name: 'yyy.png',
  39. status: 'done',
  40. url: 'http://www.baidu.com/yyy.png',
  41. },
  42. {
  43. uid: '3',
  44. name: 'zzz.png',
  45. status: 'error',
  46. response: 'Server Error 500', // custom error message to show
  47. url: 'http://www.baidu.com/zzz.png',
  48. },
  49. ]);
  50. const handleChange = ({ file, fileList }: FileInfo) => {
  51. if (file.status !== 'uploading') {
  52. console.log(file, fileList);
  53. }
  54. };
  55. return {
  56. fileList,
  57. handleChange,
  58. };
  59. },
  60. });
  61. </script>

Upload上传 - 图10Upload

Upload上传 - 图11xxx.pngUpload上传 - 图12

完全控制的上传列表

使用 fileList 对列表进行完全控制,可以实现各种自定义功能,以下演示二种情况:

  1. 上传列表数量的限制。

  2. 读取远程路径并显示链接。

  1. <template>
  2. <a-upload
  3. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  4. :multiple="true"
  5. :file-list="fileList"
  6. @change="handleChange"
  7. >
  8. <a-button>
  9. <upload-outlined></upload-outlined>
  10. Upload
  11. </a-button>
  12. </a-upload>
  13. </template>
  14. <script lang="ts">
  15. import { UploadOutlined } from '@ant-design/icons-vue';
  16. import { defineComponent, ref } from 'vue';
  17. interface FileItem {
  18. uid: string;
  19. name?: string;
  20. status?: string;
  21. response?: Response;
  22. url: string;
  23. }
  24. interface FileInfo {
  25. file: FileItem;
  26. fileList: FileItem[];
  27. }
  28. export default defineComponent({
  29. components: {
  30. UploadOutlined,
  31. },
  32. setup() {
  33. const fileList = ref<FileItem[]>([
  34. {
  35. uid: '-1',
  36. name: 'xxx.png',
  37. status: 'done',
  38. url: 'http://www.baidu.com/xxx.png',
  39. },
  40. ]);
  41. const handleChange = (info: FileInfo) => {
  42. let resFileList = [...info.fileList];
  43. // 1. Limit the number of uploaded files
  44. // Only to show two recent uploaded files, and old ones will be replaced by the new
  45. resFileList = resFileList.slice(-2);
  46. // 2. read from response and show file link
  47. resFileList = resFileList.map(file => {
  48. if (file.response) {
  49. // Component will show file.url as link
  50. file.url = file.response.url;
  51. }
  52. return file;
  53. });
  54. fileList.value = resFileList;
  55. };
  56. return {
  57. fileList,
  58. handleChange,
  59. };
  60. },
  61. });
  62. </script>

Upload上传 - 图13

图片列表样式

上传文件为图片,可展示本地缩略图。IE8/9 不支持浏览器本地缩略图展示(Ref),可以写 thumbUrl 属性来代替。

  1. <template>
  2. <div>
  3. <a-upload
  4. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  5. list-type="picture"
  6. v-model:file-list="fileList"
  7. >
  8. <a-button>
  9. <upload-outlined></upload-outlined>
  10. upload
  11. </a-button>
  12. </a-upload>
  13. <br />
  14. <br />
  15. <a-upload
  16. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  17. list-type="picture"
  18. v-model:file-list="fileList1"
  19. class="upload-list-inline"
  20. >
  21. <a-button>
  22. <upload-outlined></upload-outlined>
  23. upload
  24. </a-button>
  25. </a-upload>
  26. </div>
  27. </template>
  28. <script lang="ts">
  29. import { UploadOutlined } from '@ant-design/icons-vue';
  30. import { defineComponent, ref } from 'vue';
  31. interface FileItem {
  32. uid: string;
  33. name?: string;
  34. status?: string;
  35. response?: string;
  36. url?: string;
  37. thumbUrl?: string;
  38. }
  39. export default defineComponent({
  40. components: {
  41. UploadOutlined,
  42. },
  43. setup() {
  44. const fileList = ref<FileItem[]>([
  45. {
  46. uid: '-1',
  47. name: 'xxx.png',
  48. status: 'done',
  49. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  50. thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  51. },
  52. {
  53. uid: '-2',
  54. name: 'yyy.png',
  55. status: 'done',
  56. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  57. thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  58. },
  59. ]);
  60. const fileList1 = ref<FileItem[]>([
  61. {
  62. uid: '-1',
  63. name: 'xxx.png',
  64. status: 'done',
  65. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  66. thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  67. },
  68. {
  69. uid: '-2',
  70. name: 'yyy.png',
  71. status: 'done',
  72. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  73. thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  74. },
  75. ]);
  76. return {
  77. fileList,
  78. fileList1,
  79. };
  80. },
  81. });
  82. </script>
  83. <style scoped>
  84. /* tile uploaded pictures */
  85. .upload-list-inline :deep(.ant-upload-list-item) {
  86. float: left;
  87. width: 200px;
  88. margin-right: 8px;
  89. }
  90. .upload-list-inline :deep(.ant-upload-animate-enter) {
  91. animation-name: uploadAnimateInlineIn;
  92. }
  93. .upload-list-inline :deep(.ant-upload-animate-leave) {
  94. animation-name: uploadAnimateInlineOut;
  95. }
  96. </style>

Upload上传 - 图14Upload Directory

文件夹上传

支持上传一个文件夹里的所有文件。

  1. <template>
  2. <a-upload action="https://www.mocky.io/v2/5cc8019d300000980a055e76" directory>
  3. <a-button>
  4. <upload-outlined></upload-outlined>
  5. Upload Directory
  6. </a-button>
  7. </a-upload>
  8. </template>
  9. <script lang="ts">
  10. import { defineComponent } from 'vue';
  11. import { UploadOutlined } from '@ant-design/icons-vue';
  12. export default defineComponent({
  13. components: {
  14. UploadOutlined,
  15. },
  16. });
  17. </script>

Upload上传 - 图15

上传前转换文件

使用 beforeUpload 转换上传的文件(例如添加水印)。

  1. <template>
  2. <div>
  3. <a-upload
  4. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  5. :transform-file="transformFile"
  6. v-model:file-list="fileList"
  7. >
  8. <a-button>
  9. <upload-outlined></upload-outlined>
  10. Upload
  11. </a-button>
  12. </a-upload>
  13. </div>
  14. </template>
  15. <script lang="ts">
  16. import { UploadOutlined } from '@ant-design/icons-vue';
  17. import { defineComponent, ref } from 'vue';
  18. export default defineComponent({
  19. components: {
  20. UploadOutlined,
  21. },
  22. setup() {
  23. const transformFile = (file: any) => {
  24. return new Promise(resolve => {
  25. const reader = new FileReader();
  26. reader.readAsDataURL(file);
  27. reader.onload = () => {
  28. const canvas = document.createElement('canvas');
  29. const img: HTMLImageElement = document.createElement('img');
  30. img.src = reader.result as string;
  31. img.onload = () => {
  32. const ctx: CanvasRenderingContext2D = canvas.getContext('2d')!;
  33. ctx.drawImage(img, 0, 0);
  34. ctx.fillStyle = 'red';
  35. ctx.textBaseline = 'middle';
  36. ctx.fillText('Ant Design', 20, 20);
  37. canvas.toBlob(resolve);
  38. };
  39. };
  40. });
  41. };
  42. return {
  43. transformFile,
  44. fileList: ref([]),
  45. };
  46. },
  47. });
  48. </script>

Upload上传 - 图16

Upload

用户头像

点击上传用户头像,并使用 beforeUpload 限制用户上传的图片格式和大小。

beforeUpload 的返回值可以是一个 Promise 以支持异步处理,如服务端校验等:示例

  1. <template>
  2. <a-upload
  3. v-model:file-list="fileList"
  4. name="avatar"
  5. list-type="picture-card"
  6. class="avatar-uploader"
  7. :show-upload-list="false"
  8. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  9. :before-upload="beforeUpload"
  10. @change="handleChange"
  11. >
  12. <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
  13. <div v-else>
  14. <loading-outlined v-if="loading"></loading-outlined>
  15. <plus-outlined v-else></plus-outlined>
  16. <div class="ant-upload-text">Upload</div>
  17. </div>
  18. </a-upload>
  19. </template>
  20. <script lang="ts">
  21. import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
  22. import { message } from 'ant-design-vue';
  23. import { defineComponent, ref } from 'vue';
  24. interface FileItem {
  25. uid: string;
  26. name?: string;
  27. status?: string;
  28. response?: string;
  29. url?: string;
  30. type?: string;
  31. size: number;
  32. originFileObj: any;
  33. }
  34. interface FileInfo {
  35. file: FileItem;
  36. fileList: FileItem[];
  37. }
  38. function getBase64(img: Blob, callback: (base64Url: string) => void) {
  39. const reader = new FileReader();
  40. reader.addEventListener('load', () => callback(reader.result as string));
  41. reader.readAsDataURL(img);
  42. }
  43. export default defineComponent({
  44. components: {
  45. LoadingOutlined,
  46. PlusOutlined,
  47. },
  48. setup() {
  49. const fileList = ref([]);
  50. const loading = ref<boolean>(false);
  51. const imageUrl = ref<string>('');
  52. const handleChange = (info: FileInfo) => {
  53. if (info.file.status === 'uploading') {
  54. loading.value = true;
  55. return;
  56. }
  57. if (info.file.status === 'done') {
  58. // Get this url from response in real world.
  59. getBase64(info.file.originFileObj, (base64Url: string) => {
  60. imageUrl.value = base64Url;
  61. loading.value = false;
  62. });
  63. }
  64. if (info.file.status === 'error') {
  65. loading.value = false;
  66. message.error('upload error');
  67. }
  68. };
  69. const beforeUpload = (file: FileItem) => {
  70. const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  71. if (!isJpgOrPng) {
  72. message.error('You can only upload JPG file!');
  73. }
  74. const isLt2M = file.size / 1024 / 1024 < 2;
  75. if (!isLt2M) {
  76. message.error('Image must smaller than 2MB!');
  77. }
  78. return isJpgOrPng && isLt2M;
  79. };
  80. return {
  81. fileList,
  82. loading,
  83. imageUrl,
  84. handleChange,
  85. beforeUpload,
  86. };
  87. },
  88. });
  89. </script>
  90. <style>
  91. .avatar-uploader > .ant-upload {
  92. width: 128px;
  93. height: 128px;
  94. }
  95. .ant-upload-select-picture-card i {
  96. font-size: 32px;
  97. color: #999;
  98. }
  99. .ant-upload-select-picture-card .ant-upload-text {
  100. margin-top: 8px;
  101. color: #666;
  102. }
  103. </style>

Upload上传 - 图17

照片墙

用户可以上传图片并在列表中显示缩略图。当上传照片数到达限制后,上传按钮消失。

  1. <template>
  2. <div class="clearfix">
  3. <a-upload
  4. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  5. list-type="picture-card"
  6. v-model:file-list="fileList"
  7. @preview="handlePreview"
  8. >
  9. <div v-if="fileList.length < 8">
  10. <plus-outlined />
  11. <div class="ant-upload-text">Upload</div>
  12. </div>
  13. </a-upload>
  14. <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
  15. <img alt="example" style="width: 100%" :src="previewImage" />
  16. </a-modal>
  17. </div>
  18. </template>
  19. <script lang="ts">
  20. import { PlusOutlined } from '@ant-design/icons-vue';
  21. import { defineComponent, ref } from 'vue';
  22. function getBase64(file: File) {
  23. return new Promise((resolve, reject) => {
  24. const reader = new FileReader();
  25. reader.readAsDataURL(file);
  26. reader.onload = () => resolve(reader.result);
  27. reader.onerror = error => reject(error);
  28. });
  29. }
  30. interface FileItem {
  31. uid: string;
  32. name?: string;
  33. status?: string;
  34. response?: string;
  35. percent?: number;
  36. url?: string;
  37. preview?: string;
  38. originFileObj?: any;
  39. }
  40. interface FileInfo {
  41. file: FileItem;
  42. fileList: FileItem[];
  43. }
  44. export default defineComponent({
  45. components: {
  46. PlusOutlined,
  47. },
  48. setup() {
  49. const previewVisible = ref<boolean>(false);
  50. const previewImage = ref<string | undefined>('');
  51. const fileList = ref<FileItem[]>([
  52. {
  53. uid: '-1',
  54. name: 'image.png',
  55. status: 'done',
  56. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  57. },
  58. {
  59. uid: '-2',
  60. name: 'image.png',
  61. status: 'done',
  62. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  63. },
  64. {
  65. uid: '-3',
  66. name: 'image.png',
  67. status: 'done',
  68. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  69. },
  70. {
  71. uid: '-4',
  72. name: 'image.png',
  73. status: 'done',
  74. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  75. },
  76. {
  77. uid: '-5',
  78. name: 'image.png',
  79. status: 'error',
  80. },
  81. ]);
  82. const handleCancel = () => {
  83. previewVisible.value = false;
  84. };
  85. const handlePreview = async (file: FileItem) => {
  86. if (!file.url && !file.preview) {
  87. file.preview = (await getBase64(file.originFileObj)) as string;
  88. }
  89. previewImage.value = file.url || file.preview;
  90. previewVisible.value = true;
  91. };
  92. const handleChange = ({ fileList: newFileList }: FileInfo) => {
  93. fileList.value = newFileList;
  94. };
  95. return {
  96. previewVisible,
  97. previewImage,
  98. fileList,
  99. handleCancel,
  100. handlePreview,
  101. handleChange,
  102. };
  103. },
  104. });
  105. </script>
  106. <style>
  107. /* you can make up upload button and sample style by using stylesheets */
  108. .ant-upload-select-picture-card i {
  109. font-size: 32px;
  110. color: #999;
  111. }
  112. .ant-upload-select-picture-card .ant-upload-text {
  113. margin-top: 8px;
  114. color: #666;
  115. }
  116. </style>

Upload上传 - 图18

Click or drag file to this area to upload

Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files

拖拽上传

把文件拖入指定区域,完成上传,同样支持点击上传。

设置 multiple 后,在 IE10+ 可以一次上传多个文件。

  1. <template>
  2. <a-upload-dragger
  3. v-model:fileList="fileList"
  4. name="file"
  5. :multiple="true"
  6. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  7. @change="handleChange"
  8. >
  9. <p class="ant-upload-drag-icon">
  10. <inbox-outlined></inbox-outlined>
  11. </p>
  12. <p class="ant-upload-text">Click or drag file to this area to upload</p>
  13. <p class="ant-upload-hint">
  14. Support for a single or bulk upload. Strictly prohibit from uploading company data or other
  15. band files
  16. </p>
  17. </a-upload-dragger>
  18. </template>
  19. <script lang="ts">
  20. import { InboxOutlined } from '@ant-design/icons-vue';
  21. import { message } from 'ant-design-vue';
  22. import { defineComponent, ref } from 'vue';
  23. interface FileItem {
  24. uid: string;
  25. name?: string;
  26. status?: string;
  27. response?: string;
  28. url?: string;
  29. }
  30. interface FileInfo {
  31. file: FileItem;
  32. fileList: FileItem[];
  33. }
  34. export default defineComponent({
  35. components: {
  36. InboxOutlined,
  37. },
  38. setup() {
  39. const handleChange = (info: FileInfo) => {
  40. const status = info.file.status;
  41. if (status !== 'uploading') {
  42. console.log(info.file, info.fileList);
  43. }
  44. if (status === 'done') {
  45. message.success(`${info.file.name} file uploaded successfully.`);
  46. } else if (status === 'error') {
  47. message.error(`${info.file.name} file upload failed.`);
  48. }
  49. };
  50. return {
  51. handleChange,
  52. fileList: ref([]),
  53. };
  54. },
  55. });
  56. </script>

Upload上传 - 图19

手动上传

beforeUpload 返回 false 后,手动上传文件。

  1. <template>
  2. <div class="clearfix">
  3. <a-upload
  4. :file-list="fileList"
  5. :remove="handleRemove"
  6. :before-upload="beforeUpload"
  7. v-model:file-list="fileList"
  8. >
  9. <a-button>
  10. <upload-outlined></upload-outlined>
  11. Select File
  12. </a-button>
  13. </a-upload>
  14. <a-button
  15. type="primary"
  16. :disabled="fileList.length === 0"
  17. :loading="uploading"
  18. style="margin-top: 16px"
  19. @click="handleUpload"
  20. >
  21. {{ uploading ? 'Uploading' : 'Start Upload' }}
  22. </a-button>
  23. </div>
  24. </template>
  25. <script lang="ts">
  26. import request from 'umi-request';
  27. import { UploadOutlined } from '@ant-design/icons-vue';
  28. import { message } from 'ant-design-vue';
  29. import { defineComponent, ref } from 'vue';
  30. interface FileItem {
  31. uid: string;
  32. name?: string;
  33. status?: string;
  34. response?: string;
  35. url?: string;
  36. preview?: string;
  37. originFileObj?: any;
  38. file: string | Blob;
  39. }
  40. export default defineComponent({
  41. components: {
  42. UploadOutlined,
  43. },
  44. setup() {
  45. const fileList = ref<FileItem[]>([]);
  46. const uploading = ref<boolean>(false);
  47. const handleRemove = (file: FileItem) => {
  48. const index = fileList.value.indexOf(file);
  49. const newFileList = fileList.value.slice();
  50. newFileList.splice(index, 1);
  51. fileList.value = newFileList;
  52. };
  53. const beforeUpload = (file: FileItem) => {
  54. fileList.value = [...fileList.value, file];
  55. return false;
  56. };
  57. const handleUpload = () => {
  58. const formData = new FormData();
  59. fileList.value.forEach(({ file }: FileItem) => {
  60. formData.append('files[]', file);
  61. });
  62. uploading.value = true;
  63. // You can use any AJAX library you like
  64. request('https://www.mocky.io/v2/5cc8019d300000980a055e76', {
  65. method: 'post',
  66. data: formData,
  67. })
  68. .then(() => {
  69. fileList.value = [];
  70. uploading.value = false;
  71. message.success('upload successfully.');
  72. })
  73. .catch(() => {
  74. uploading.value = false;
  75. message.error('upload failed.');
  76. });
  77. };
  78. return {
  79. fileList,
  80. uploading,
  81. handleRemove,
  82. beforeUpload,
  83. handleUpload,
  84. };
  85. },
  86. });
  87. </script>

Upload上传 - 图20

自定义预览

自定义本地预览,用于处理非图片格式文件(例如视频文件)。

  1. <template>
  2. <div>
  3. <a-upload
  4. list-type="picture"
  5. action="//jsonplaceholder.typicode.com/posts/"
  6. :preview-file="previewFile"
  7. v-model:file-list="fileList"
  8. >
  9. <a-button>
  10. <upload-outlined></upload-outlined>
  11. Upload
  12. </a-button>
  13. </a-upload>
  14. </div>
  15. </template>
  16. <script lang="ts">
  17. import { UploadOutlined } from '@ant-design/icons-vue';
  18. import { defineComponent, ref } from 'vue';
  19. export default defineComponent({
  20. components: {
  21. UploadOutlined,
  22. },
  23. setup() {
  24. const previewFile = async (file: any): Promise<Response> => {
  25. console.log('Your upload file:', file);
  26. // Your process logic. Here we just mock to the same file
  27. const res = await fetch('https://next.json-generator.com/api/json/get/4ytyBoLK8', {
  28. method: 'POST',
  29. body: file,
  30. });
  31. const { thumbnail } = await res.json();
  32. return thumbnail;
  33. };
  34. return {
  35. previewFile,
  36. fileList: ref([]),
  37. };
  38. },
  39. });
  40. </script>

API

参数说明类型默认值版本
accept接受上传的文件类型, 详见 input accept Attributestring
action上传的地址string|(file) => Promise
method上传请求的 http methodstring‘post’1.5.0
directory支持上传文件夹(caniusebooleanfalse
beforeUpload上传文件之前的钩子,参数为上传的文件,若返回 false 则停止上传。支持返回一个 Promise 对象,Promise 对象 reject 时则停止上传,resolve 时开始上传( resolve 传入 FileBlob 对象则上传 resolve 传入对象)。注意:IE9 不支持该方法(file, fileList) => boolean | Promise
customRequest通过覆盖默认的上传行为,可以自定义自己的上传实现Function
data上传所需参数或返回上传参数的方法object|(file) => object
disabled是否禁用booleanfalse
fileList已经上传的文件列表(受控)object[]
headers设置上传的请求头部,IE10 以上有效object
listType上传列表的内建样式,支持三种基本样式 text, picturepicture-cardstring‘text’
multiple是否支持多选文件,ie10+ 支持。开启后按住 ctrl 可选择多个文件。booleanfalse
name发到后台的文件参数名string‘file’
previewFile自定义文件预览逻辑(file: File | Blob) => Promise<dataURL: string>1.5.0
showUploadList是否展示 uploadList, 可设为一个对象,用于单独设定 showPreviewIcon 和 showRemoveIconBoolean or { showPreviewIcon?: boolean, showRemoveIcon?: boolean }true
supportServerRender服务端渲染时需要打开这个booleanfalse
withCredentials上传请求时是否携带 cookiebooleanfalse
openFileDialogOnClick点击打开文件对话框booleantrue
remove点击移除文件时的回调,返回值为 false 时不移除。支持返回一个 Promise 对象,Promise 对象 resolve(false) 或 reject 时不移除。Function(file): boolean | Promise
transformFile在上传之前转换文件。支持返回一个 Promise 对象Function(file): string | Blob | File | Promise<string | Blob | File>1.5.0

事件

事件名称说明回调参数版本
change上传文件改变时的状态,详见 changeFunction
preview点击文件链接或预览图标时的回调Function(file)
download点击下载文件时的回调,如果没有指定,则默认跳转到文件 url 对应的标签页。Function(file): void跳转新标签页
reject拖拽文件不符合 accept 类型时的回调Function(fileList)

change

上传中、完成、失败都会调用这个函数。

文件状态改变的回调,返回为:

  1. {
  2. file: { /* ... */ },
  3. fileList: [ /* ... */ ],
  4. event: { /* ... */ },
  5. }
  1. file 当前操作的文件对象。

    1. {
    2. uid: 'uid', // 文件唯一标识,建议设置为负数,防止和内部产生的 id 冲突
    3. name: 'xx.png', // 文件名
    4. status: 'done', // 状态有:uploading done error removed
    5. response: '{"status": "success"}', // 服务端响应内容
    6. linkProps: '{"download": "image"}', // 下载链接额外的 HTML 属性
    7. xhr: 'XMLHttpRequest{ ... }', // XMLHttpRequest Header
    8. }
  2. fileList 当前的文件列表。

  3. event 上传中的服务端响应内容,包含了上传进度等信息,高级浏览器支持。