• 上传
    • 何时使用
    • 代码演示
      • 点击上传
      • 用户头像
      • 已上传的文件列表
      • 照片墙
      • 完全控制的上传列表
      • 拖拽上传
      • 图片列表样式
      • 手动上传
      • 文件夹上传
  • API
    • 事件
    • change

    上传

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

    何时使用

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

    代码演示

    Upload 上传 - 图1

    点击上传

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

    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 上传 - 图2

    用户头像

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

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

    Upload 上传 - 图3

    已上传的文件列表

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

    1. <template>
    2. <a-upload
    3. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
    4. :defaultFileList="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 上传 - 图4

    照片墙

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

    1. <template>
    2. <div class="clearfix">
    3. <a-upload
    4. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
    5. listType="picture-card"
    6. :fileList="fileList"
    7. @preview="handlePreview"
    8. @change="handleChange"
    9. >
    10. <div v-if="fileList.length < 3">
    11. <a-icon type="plus" />
    12. <div class="ant-upload-text">Upload</div>
    13. </div>
    14. </a-upload>
    15. <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
    16. <img alt="example" style="width: 100%" :src="previewImage" />
    17. </a-modal>
    18. </div>
    19. </template>
    20. <script>
    21. export default {
    22. data() {
    23. return {
    24. previewVisible: false,
    25. previewImage: '',
    26. fileList: [
    27. {
    28. uid: '-1',
    29. name: 'xxx.png',
    30. status: 'done',
    31. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    32. },
    33. ],
    34. };
    35. },
    36. methods: {
    37. handleCancel() {
    38. this.previewVisible = false;
    39. },
    40. handlePreview(file) {
    41. this.previewImage = file.url || file.thumbUrl;
    42. this.previewVisible = true;
    43. },
    44. handleChange({ fileList }) {
    45. this.fileList = fileList;
    46. },
    47. },
    48. };
    49. </script>
    50. <style>
    51. /* you can make up upload button and sample style by using stylesheets */
    52. .ant-upload-select-picture-card i {
    53. font-size: 32px;
    54. color: #999;
    55. }
    56. .ant-upload-select-picture-card .ant-upload-text {
    57. margin-top: 8px;
    58. color: #666;
    59. }
    60. </style>

    Upload 上传 - 图5

    完全控制的上传列表

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

    • 上传列表数量的限制。
    • 读取远程路径并显示链接。
    • 按照服务器返回信息筛选成功上传的文件。
    1. <template>
    2. <a-upload
    3. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
    4. :multiple="true"
    5. :fileList="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 上传 - 图6

    拖拽上传

    把文件拖入指定区域,完成上传,同样支持点击上传。设置 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">Click or drag file to this area to upload</p>
    12. <p class="ant-upload-hint">
    13. Support for a single or bulk upload. Strictly prohibit from uploading company data or other
    14. band files
    15. </p>
    16. </a-upload-dragger>
    17. </template>
    18. <script>
    19. export default {
    20. data() {
    21. return {};
    22. },
    23. methods: {
    24. handleChange(info) {
    25. const status = info.file.status;
    26. if (status !== 'uploading') {
    27. console.log(info.file, info.fileList);
    28. }
    29. if (status === 'done') {
    30. this.$message.success(`${info.file.name} file uploaded successfully.`);
    31. } else if (status === 'error') {
    32. this.$message.error(`${info.file.name} file upload failed.`);
    33. }
    34. },
    35. },
    36. };
    37. </script>

    Upload 上传 - 图7

    图片列表样式

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

    1. <template>
    2. <div>
    3. <a-upload
    4. action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
    5. listType="picture"
    6. :defaultFileList="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. listType="picture"
    15. :defaultFileList="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:
    33. 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    34. },
    35. {
    36. uid: '-2',
    37. name: 'yyy.png',
    38. status: 'done',
    39. url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    40. thumbUrl:
    41. 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    42. },
    43. ],
    44. };
    45. },
    46. };
    47. </script>
    48. <style scoped>
    49. /* tile uploaded pictures */
    50. .upload-list-inline >>> .ant-upload-list-item {
    51. float: left;
    52. width: 200px;
    53. margin-right: 8px;
    54. }
    55. .upload-list-inline >>> .ant-upload-animate-enter {
    56. animation-name: uploadAnimateInlineIn;
    57. }
    58. .upload-list-inline >>> .ant-upload-animate-leave {
    59. animation-name: uploadAnimateInlineOut;
    60. }
    61. </style>

    Upload 上传 - 图8

    手动上传

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

    1. <template>
    2. <div class="clearfix">
    3. <a-upload :fileList="fileList" :remove="handleRemove" :beforeUpload="beforeUpload">
    4. <a-button> <a-icon type="upload" /> Select File </a-button>
    5. </a-upload>
    6. <a-button
    7. type="primary"
    8. @click="handleUpload"
    9. :disabled="fileList.length === 0"
    10. :loading="uploading"
    11. style="margin-top: 16px"
    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 上传 - 图9

    文件夹上传

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

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

    API

    参数说明类型默认值
    accept接受上传的文件类型, 详见 input accept Attributestring
    action上传的地址string|(file) => Promise
    directory支持上传文件夹(caniuse)booleanfalse
    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'
    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

    事件

    事件名称说明回调参数
    change上传文件改变时的状态,详见 changeFunction
    preview点击文件链接或预览图标时的回调Function(file)
    reject拖拽文件不符合 accept 类型时的回调Function(fileList)

    change

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

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

    {
      file: { /* ... */ },
      fileList: [ /* ... */ ],
      event: { /* ... */ },
    }
    
    • file 当前操作的文件对象。
    {
       uid: 'uid',      // 文件唯一标识,建议设置为负数,防止和内部产生的 id 冲突
       name: 'xx.png'   // 文件名
       status: 'done', // 状态有:uploading done error removed
       response: '{"status": "success"}', // 服务端响应内容
       linkProps: '{"download": "image"}', // 下载链接额外的 HTML 属性
    }
    
    • fileList 当前的文件列表。

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