上传

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

何时使用

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

    代码演示

Upload上传 - 图1Click to Upload

点击上传

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

  1. <template>
  2. <a-upload
  3. name="file"
  4. :multiple="true"
  5. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  6. :headers="headers"
  7. @change="handleChange"
  8. >
  9. <a-button> <a-icon type="upload" /> Click to Upload </a-button>
  10. </a-upload>
  11. </template>
  12. <script>
  13. export default {
  14. data() {
  15. return {
  16. headers: {
  17. authorization: 'authorization-text',
  18. },
  19. };
  20. },
  21. methods: {
  22. handleChange(info) {
  23. if (info.file.status !== 'uploading') {
  24. console.log(info.file, info.fileList);
  25. }
  26. if (info.file.status === 'done') {
  27. this.$message.success(`${info.file.name} file uploaded successfully`);
  28. } else if (info.file.status === 'error') {
  29. this.$message.error(`${info.file.name} file upload failed.`);
  30. }
  31. },
  32. },
  33. };
  34. </script>

Upload上传 - 图2Upload

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

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

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

已上传的文件列表

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

  1. <template>
  2. <a-upload
  3. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  4. :default-file-list="defaultFileList"
  5. >
  6. <a-button> <a-icon type="upload" /> Upload </a-button>
  7. </a-upload>
  8. </template>
  9. <script>
  10. export default {
  11. data() {
  12. return {
  13. defaultFileList: [
  14. {
  15. uid: '1',
  16. name: 'xxx.png',
  17. status: 'done',
  18. response: 'Server Error 500', // custom error message to show
  19. url: 'http://www.baidu.com/xxx.png',
  20. },
  21. {
  22. uid: '2',
  23. name: 'yyy.png',
  24. status: 'done',
  25. url: 'http://www.baidu.com/yyy.png',
  26. },
  27. {
  28. uid: '3',
  29. name: 'zzz.png',
  30. status: 'error',
  31. response: 'Server Error 500', // custom error message to show
  32. url: 'http://www.baidu.com/zzz.png',
  33. },
  34. ],
  35. };
  36. },
  37. methods: {
  38. handleChange({ file, fileList }) {
  39. if (file.status !== 'uploading') {
  40. console.log(file, fileList);
  41. }
  42. },
  43. },
  44. };
  45. </script>

Upload上传 - 图9Upload

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

完全控制的上传列表

使用 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> <a-icon type="upload" /> Upload </a-button>
  9. </a-upload>
  10. </template>
  11. <script>
  12. export default {
  13. data() {
  14. return {
  15. fileList: [
  16. {
  17. uid: '-1',
  18. name: 'xxx.png',
  19. status: 'done',
  20. url: 'http://www.baidu.com/xxx.png',
  21. },
  22. ],
  23. };
  24. },
  25. methods: {
  26. handleChange(info) {
  27. let fileList = [...info.fileList];
  28. // 1. Limit the number of uploaded files
  29. // Only to show two recent uploaded files, and old ones will be replaced by the new
  30. fileList = fileList.slice(-2);
  31. // 2. read from response and show file link
  32. fileList = fileList.map(file => {
  33. if (file.response) {
  34. // Component will show file.url as link
  35. file.url = file.response.url;
  36. }
  37. return file;
  38. });
  39. this.fileList = fileList;
  40. },
  41. },
  42. };
  43. </script>

Upload上传 - 图12

图片列表样式

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

  1. <template>
  2. <div>
  3. <a-upload
  4. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  5. list-type="picture"
  6. :default-file-list="fileList"
  7. >
  8. <a-button> <a-icon type="upload" /> upload </a-button>
  9. </a-upload>
  10. <br />
  11. <br />
  12. <a-upload
  13. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  14. list-type="picture"
  15. :default-file-list="fileList"
  16. class="upload-list-inline"
  17. >
  18. <a-button> <a-icon type="upload" /> upload </a-button>
  19. </a-upload>
  20. </div>
  21. </template>
  22. <script>
  23. export default {
  24. data() {
  25. return {
  26. fileList: [
  27. {
  28. uid: '-1',
  29. name: 'xxx.png',
  30. status: 'done',
  31. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  32. thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  33. },
  34. {
  35. uid: '-2',
  36. name: 'yyy.png',
  37. status: 'done',
  38. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  39. thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
  40. },
  41. ],
  42. };
  43. },
  44. };
  45. </script>
  46. <style scoped>
  47. /* tile uploaded pictures */
  48. .upload-list-inline >>> .ant-upload-list-item {
  49. float: left;
  50. width: 200px;
  51. margin-right: 8px;
  52. }
  53. .upload-list-inline >>> .ant-upload-animate-enter {
  54. animation-name: uploadAnimateInlineIn;
  55. }
  56. .upload-list-inline >>> .ant-upload-animate-leave {
  57. animation-name: uploadAnimateInlineOut;
  58. }
  59. </style>

Upload上传 - 图13Upload Directory

文件夹上传

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

  1. <template>
  2. <a-upload action="https://www.mocky.io/v2/5cc8019d300000980a055e76" directory>
  3. <a-button> <a-icon type="upload" /> Upload Directory </a-button>
  4. </a-upload>
  5. </template>

Upload上传 - 图14

上传前转换文件

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

  1. <template>
  2. <div>
  3. <a-upload
  4. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  5. :transform-file="transformFile"
  6. >
  7. <a-button> <a-icon type="upload" /> Upload </a-button>
  8. </a-upload>
  9. </div>
  10. </template>
  11. <script>
  12. export default {
  13. methods: {
  14. transformFile(file) {
  15. return new Promise(resolve => {
  16. const reader = new FileReader();
  17. reader.readAsDataURL(file);
  18. reader.onload = () => {
  19. const canvas = document.createElement('canvas');
  20. const img = document.createElement('img');
  21. img.src = reader.result;
  22. img.onload = () => {
  23. const ctx = canvas.getContext('2d');
  24. ctx.drawImage(img, 0, 0);
  25. ctx.fillStyle = 'red';
  26. ctx.textBaseline = 'middle';
  27. ctx.fillText('Ant Design', 20, 20);
  28. canvas.toBlob(resolve);
  29. };
  30. };
  31. });
  32. },
  33. },
  34. };
  35. </script>

Upload上传 - 图15

Upload

用户头像

点击上传用户头像,并使用 beforeUpload 限制用户上传的图片格式和大小。
beforeUpload 的返回值可以是一个 Promise 以支持异步处理,如服务端校验等

  1. <template>
  2. <a-upload
  3. name="avatar"
  4. list-type="picture-card"
  5. class="avatar-uploader"
  6. :show-upload-list="false"
  7. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  8. :before-upload="beforeUpload"
  9. @change="handleChange"
  10. >
  11. <img v-if="imageUrl" :src="imageUrl" alt="avatar" />
  12. <div v-else>
  13. <a-icon :type="loading ? 'loading' : 'plus'" />
  14. <div class="ant-upload-text">
  15. Upload
  16. </div>
  17. </div>
  18. </a-upload>
  19. </template>
  20. <script>
  21. function getBase64(img, callback) {
  22. const reader = new FileReader();
  23. reader.addEventListener('load', () => callback(reader.result));
  24. reader.readAsDataURL(img);
  25. }
  26. export default {
  27. data() {
  28. return {
  29. loading: false,
  30. imageUrl: '',
  31. };
  32. },
  33. methods: {
  34. handleChange(info) {
  35. if (info.file.status === 'uploading') {
  36. this.loading = true;
  37. return;
  38. }
  39. if (info.file.status === 'done') {
  40. // Get this url from response in real world.
  41. getBase64(info.file.originFileObj, imageUrl => {
  42. this.imageUrl = imageUrl;
  43. this.loading = false;
  44. });
  45. }
  46. },
  47. beforeUpload(file) {
  48. const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  49. if (!isJpgOrPng) {
  50. this.$message.error('You can only upload JPG file!');
  51. }
  52. const isLt2M = file.size / 1024 / 1024 < 2;
  53. if (!isLt2M) {
  54. this.$message.error('Image must smaller than 2MB!');
  55. }
  56. return isJpgOrPng && isLt2M;
  57. },
  58. },
  59. };
  60. </script>
  61. <style>
  62. .avatar-uploader > .ant-upload {
  63. width: 128px;
  64. height: 128px;
  65. }
  66. .ant-upload-select-picture-card i {
  67. font-size: 32px;
  68. color: #999;
  69. }
  70. .ant-upload-select-picture-card .ant-upload-text {
  71. margin-top: 8px;
  72. color: #666;
  73. }
  74. </style>

Upload上传 - 图16

照片墙

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

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

Upload上传 - 图17

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. name="file"
  4. :multiple="true"
  5. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
  6. @change="handleChange"
  7. >
  8. <p class="ant-upload-drag-icon">
  9. <a-icon type="inbox" />
  10. </p>
  11. <p class="ant-upload-text">
  12. Click or drag file to this area to upload
  13. </p>
  14. <p class="ant-upload-hint">
  15. Support for a single or bulk upload. Strictly prohibit from uploading company data or other
  16. band files
  17. </p>
  18. </a-upload-dragger>
  19. </template>
  20. <script>
  21. export default {
  22. data() {
  23. return {};
  24. },
  25. methods: {
  26. handleChange(info) {
  27. const status = info.file.status;
  28. if (status !== 'uploading') {
  29. console.log(info.file, info.fileList);
  30. }
  31. if (status === 'done') {
  32. this.$message.success(`${info.file.name} file uploaded successfully.`);
  33. } else if (status === 'error') {
  34. this.$message.error(`${info.file.name} file upload failed.`);
  35. }
  36. },
  37. },
  38. };
  39. </script>

Upload上传 - 图18

手动上传

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

  1. <template>
  2. <div class="clearfix">
  3. <a-upload :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
  4. <a-button> <a-icon type="upload" /> Select File </a-button>
  5. </a-upload>
  6. <a-button
  7. type="primary"
  8. :disabled="fileList.length === 0"
  9. :loading="uploading"
  10. style="margin-top: 16px"
  11. @click="handleUpload"
  12. >
  13. {{ uploading ? 'Uploading' : 'Start Upload' }}
  14. </a-button>
  15. </div>
  16. </template>
  17. <script>
  18. import reqwest from 'reqwest';
  19. export default {
  20. data() {
  21. return {
  22. fileList: [],
  23. uploading: false,
  24. };
  25. },
  26. methods: {
  27. handleRemove(file) {
  28. const index = this.fileList.indexOf(file);
  29. const newFileList = this.fileList.slice();
  30. newFileList.splice(index, 1);
  31. this.fileList = newFileList;
  32. },
  33. beforeUpload(file) {
  34. this.fileList = [...this.fileList, file];
  35. return false;
  36. },
  37. handleUpload() {
  38. const { fileList } = this;
  39. const formData = new FormData();
  40. fileList.forEach(file => {
  41. formData.append('files[]', file);
  42. });
  43. this.uploading = true;
  44. // You can use any AJAX library you like
  45. reqwest({
  46. url: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  47. method: 'post',
  48. processData: false,
  49. data: formData,
  50. success: () => {
  51. this.fileList = [];
  52. this.uploading = false;
  53. this.$message.success('upload successfully.');
  54. },
  55. error: () => {
  56. this.uploading = false;
  57. this.$message.error('upload failed.');
  58. },
  59. });
  60. },
  61. },
  62. };
  63. </script>

Upload上传 - 图19

自定义预览

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

  1. <template>
  2. <div>
  3. <a-upload
  4. list-type="picture"
  5. action="//jsonplaceholder.typicode.com/posts/"
  6. :preview-file="previewFile"
  7. >
  8. <a-button> <a-icon type="upload" /> Upload </a-button>
  9. </a-upload>
  10. </div>
  11. </template>
  12. <script>
  13. export default {
  14. methods: {
  15. previewFile(file) {
  16. console.log('Your upload file:', file);
  17. // Your process logic. Here we just mock to the same file
  18. return fetch('https://next.json-generator.com/api/json/get/4ytyBoLK8', {
  19. method: 'POST',
  20. body: file,
  21. })
  22. .then(res => res.json())
  23. .then(({ thumbnail }) => thumbnail);
  24. },
  25. },
  26. };
  27. </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
defaultFileList默认已经上传的文件列表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 上传中的服务端响应内容,包含了上传进度等信息,高级浏览器支持。