上传
上传是将信息(网页、文字、图片、视频等)通过网页或者上传工具发布到远程服务器上的过程。
何时使用
Click to Upload
点击上传
经典款式,用户点击按钮弹出文件选择框。
<template>
<a-upload
name="file"
:multiple="true"
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
:headers="headers"
@change="handleChange"
>
<a-button> <a-icon type="upload" /> Click to Upload </a-button>
</a-upload>
</template>
<script>
export default {
data() {
return {
headers: {
authorization: 'authorization-text',
},
};
},
methods: {
handleChange(info) {
if (info.file.status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (info.file.status === 'done') {
this.$message.success(`${info.file.name} file uploaded successfully`);
} else if (info.file.status === 'error') {
this.$message.error(`${info.file.name} file upload failed.`);
}
},
},
};
</script>
Upload
已上传的文件列表
使用 defaultFileList
设置已上传的内容。
<template>
<a-upload
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
:default-file-list="defaultFileList"
>
<a-button> <a-icon type="upload" /> Upload </a-button>
</a-upload>
</template>
<script>
export default {
data() {
return {
defaultFileList: [
{
uid: '1',
name: 'xxx.png',
status: 'done',
response: 'Server Error 500', // custom error message to show
url: 'http://www.baidu.com/xxx.png',
},
{
uid: '2',
name: 'yyy.png',
status: 'done',
url: 'http://www.baidu.com/yyy.png',
},
{
uid: '3',
name: 'zzz.png',
status: 'error',
response: 'Server Error 500', // custom error message to show
url: 'http://www.baidu.com/zzz.png',
},
],
};
},
methods: {
handleChange({ file, fileList }) {
if (file.status !== 'uploading') {
console.log(file, fileList);
}
},
},
};
</script>
Upload
完全控制的上传列表
使用 fileList
对列表进行完全控制,可以实现各种自定义功能,以下演示三种情况:
- 上传列表数量的限制。
- 读取远程路径并显示链接。
<template>
<a-upload
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
:multiple="true"
:file-list="fileList"
@change="handleChange"
>
<a-button> <a-icon type="upload" /> Upload </a-button>
</a-upload>
</template>
<script>
export default {
data() {
return {
fileList: [
{
uid: '-1',
name: 'xxx.png',
status: 'done',
url: 'http://www.baidu.com/xxx.png',
},
],
};
},
methods: {
handleChange(info) {
let fileList = [...info.fileList];
// 1. Limit the number of uploaded files
// Only to show two recent uploaded files, and old ones will be replaced by the new
fileList = fileList.slice(-2);
// 2. read from response and show file link
fileList = fileList.map(file => {
if (file.response) {
// Component will show file.url as link
file.url = file.response.url;
}
return file;
});
this.fileList = fileList;
},
},
};
</script>
图片列表样式
上传文件为图片,可展示本地缩略图。IE8/9
不支持浏览器本地缩略图展示(Ref),可以写 thumbUrl
属性来代替。
<template>
<div>
<a-upload
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
list-type="picture"
:default-file-list="fileList"
>
<a-button> <a-icon type="upload" /> upload </a-button>
</a-upload>
<br />
<br />
<a-upload
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
list-type="picture"
:default-file-list="fileList"
class="upload-list-inline"
>
<a-button> <a-icon type="upload" /> upload </a-button>
</a-upload>
</div>
</template>
<script>
export default {
data() {
return {
fileList: [
{
uid: '-1',
name: 'xxx.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-2',
name: 'yyy.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
],
};
},
};
</script>
<style scoped>
/* tile uploaded pictures */
.upload-list-inline >>> .ant-upload-list-item {
float: left;
width: 200px;
margin-right: 8px;
}
.upload-list-inline >>> .ant-upload-animate-enter {
animation-name: uploadAnimateInlineIn;
}
.upload-list-inline >>> .ant-upload-animate-leave {
animation-name: uploadAnimateInlineOut;
}
</style>
Upload Directory
文件夹上传
支持上传一个文件夹里的所有文件。
<template>
<a-upload action="https://www.mocky.io/v2/5cc8019d300000980a055e76" directory>
<a-button> <a-icon type="upload" /> Upload Directory </a-button>
</a-upload>
</template>
上传前转换文件
使用 transformFile
转换上传的文件(例如添加水印)。
<template>
<div>
<a-upload
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
:transform-file="transformFile"
>
<a-button> <a-icon type="upload" /> Upload </a-button>
</a-upload>
</div>
</template>
<script>
export default {
methods: {
transformFile(file) {
return new Promise(resolve => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const canvas = document.createElement('canvas');
const img = document.createElement('img');
img.src = reader.result;
img.onload = () => {
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
ctx.fillStyle = 'red';
ctx.textBaseline = 'middle';
ctx.fillText('Ant Design', 20, 20);
canvas.toBlob(resolve);
};
};
});
},
},
};
</script>
Upload
用户头像
点击上传用户头像,并使用 beforeUpload
限制用户上传的图片格式和大小。beforeUpload
的返回值可以是一个 Promise 以支持异步处理,如服务端校验等
<template>
<a-upload
name="avatar"
list-type="picture-card"
class="avatar-uploader"
:show-upload-list="false"
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
:before-upload="beforeUpload"
@change="handleChange"
>
<img v-if="imageUrl" :src="imageUrl" alt="avatar" />
<div v-else>
<a-icon :type="loading ? 'loading' : 'plus'" />
<div class="ant-upload-text">
Upload
</div>
</div>
</a-upload>
</template>
<script>
function getBase64(img, callback) {
const reader = new FileReader();
reader.addEventListener('load', () => callback(reader.result));
reader.readAsDataURL(img);
}
export default {
data() {
return {
loading: false,
imageUrl: '',
};
},
methods: {
handleChange(info) {
if (info.file.status === 'uploading') {
this.loading = true;
return;
}
if (info.file.status === 'done') {
// Get this url from response in real world.
getBase64(info.file.originFileObj, imageUrl => {
this.imageUrl = imageUrl;
this.loading = false;
});
}
},
beforeUpload(file) {
const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
if (!isJpgOrPng) {
this.$message.error('You can only upload JPG file!');
}
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error('Image must smaller than 2MB!');
}
return isJpgOrPng && isLt2M;
},
},
};
</script>
<style>
.avatar-uploader > .ant-upload {
width: 128px;
height: 128px;
}
.ant-upload-select-picture-card i {
font-size: 32px;
color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
margin-top: 8px;
color: #666;
}
</style>
照片墙
用户可以上传图片并在列表中显示缩略图。当上传照片数到达限制后,上传按钮消失。
<template>
<div class="clearfix">
<a-upload
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
list-type="picture-card"
:file-list="fileList"
@preview="handlePreview"
@change="handleChange"
>
<div v-if="fileList.length < 8">
<a-icon type="plus" />
<div class="ant-upload-text">
Upload
</div>
</div>
</a-upload>
<a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
<img alt="example" style="width: 100%" :src="previewImage" />
</a-modal>
</div>
</template>
<script>
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
export default {
data() {
return {
previewVisible: false,
previewImage: '',
fileList: [
{
uid: '-1',
name: 'image.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-2',
name: 'image.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-3',
name: 'image.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-4',
name: 'image.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
},
{
uid: '-5',
name: 'image.png',
status: 'error',
},
],
};
},
methods: {
handleCancel() {
this.previewVisible = false;
},
async handlePreview(file) {
if (!file.url && !file.preview) {
file.preview = await getBase64(file.originFileObj);
}
this.previewImage = file.url || file.preview;
this.previewVisible = true;
},
handleChange({ fileList }) {
this.fileList = fileList;
},
},
};
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
font-size: 32px;
color: #999;
}
.ant-upload-select-picture-card .ant-upload-text {
margin-top: 8px;
color: #666;
}
</style>
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+
可以一次上传多个文件。
<template>
<a-upload-dragger
name="file"
:multiple="true"
action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
@change="handleChange"
>
<p class="ant-upload-drag-icon">
<a-icon type="inbox" />
</p>
<p class="ant-upload-text">
Click or drag file to this area to upload
</p>
<p class="ant-upload-hint">
Support for a single or bulk upload. Strictly prohibit from uploading company data or other
band files
</p>
</a-upload-dragger>
</template>
<script>
export default {
data() {
return {};
},
methods: {
handleChange(info) {
const status = info.file.status;
if (status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (status === 'done') {
this.$message.success(`${info.file.name} file uploaded successfully.`);
} else if (status === 'error') {
this.$message.error(`${info.file.name} file upload failed.`);
}
},
},
};
</script>
手动上传
beforeUpload
返回 false
后,手动上传文件。
<template>
<div class="clearfix">
<a-upload :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
<a-button> <a-icon type="upload" /> Select File </a-button>
</a-upload>
<a-button
type="primary"
:disabled="fileList.length === 0"
:loading="uploading"
style="margin-top: 16px"
@click="handleUpload"
>
{{ uploading ? 'Uploading' : 'Start Upload' }}
</a-button>
</div>
</template>
<script>
import reqwest from 'reqwest';
export default {
data() {
return {
fileList: [],
uploading: false,
};
},
methods: {
handleRemove(file) {
const index = this.fileList.indexOf(file);
const newFileList = this.fileList.slice();
newFileList.splice(index, 1);
this.fileList = newFileList;
},
beforeUpload(file) {
this.fileList = [...this.fileList, file];
return false;
},
handleUpload() {
const { fileList } = this;
const formData = new FormData();
fileList.forEach(file => {
formData.append('files[]', file);
});
this.uploading = true;
// You can use any AJAX library you like
reqwest({
url: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
method: 'post',
processData: false,
data: formData,
success: () => {
this.fileList = [];
this.uploading = false;
this.$message.success('upload successfully.');
},
error: () => {
this.uploading = false;
this.$message.error('upload failed.');
},
});
},
},
};
</script>
自定义预览
自定义本地预览,用于处理非图片格式文件(例如视频文件)。
<template>
<div>
<a-upload
list-type="picture"
action="//jsonplaceholder.typicode.com/posts/"
:preview-file="previewFile"
>
<a-button> <a-icon type="upload" /> Upload </a-button>
</a-upload>
</div>
</template>
<script>
export default {
methods: {
previewFile(file) {
console.log('Your upload file:', file);
// Your process logic. Here we just mock to the same file
return fetch('https://next.json-generator.com/api/json/get/4ytyBoLK8', {
method: 'POST',
body: file,
})
.then(res => res.json())
.then(({ thumbnail }) => thumbnail);
},
},
};
</script>
API
参数 | 说明 | 类型 | 默认值 | 版本 |
---|---|---|---|---|
accept | 接受上传的文件类型, 详见 input accept Attribute | string | 无 | |
action | 上传的地址 | string|(file) => Promise | 无 | |
method | 上传请求的 http method | string | ‘post’ | 1.5.0 |
directory | 支持上传文件夹(caniuse) | boolean | false | |
beforeUpload | 上传文件之前的钩子,参数为上传的文件,若返回 false 则停止上传。支持返回一个 Promise 对象,Promise 对象 reject 时则停止上传,resolve 时开始上传( resolve 传入 File 或 Blob 对象则上传 resolve 传入对象)。注意:IE9 不支持该方法。 | (file, fileList) => boolean | Promise | 无 | |
customRequest | 通过覆盖默认的上传行为,可以自定义自己的上传实现 | Function | 无 | |
data | 上传所需参数或返回上传参数的方法 | object|(file) => object | 无 | |
defaultFileList | 默认已经上传的文件列表 | object[] | 无 | |
disabled | 是否禁用 | boolean | false | |
fileList | 已经上传的文件列表(受控) | object[] | 无 | |
headers | 设置上传的请求头部,IE10 以上有效 | object | 无 | |
listType | 上传列表的内建样式,支持三种基本样式 text , picture 和 picture-card | string | ‘text’ | |
multiple | 是否支持多选文件,ie10+ 支持。开启后按住 ctrl 可选择多个文件。 | boolean | false | |
name | 发到后台的文件参数名 | string | ‘file’ | |
previewFile | 自定义文件预览逻辑 | (file: File | Blob) => Promise<dataURL: string> | 无 | 1.5.0 |
showUploadList | 是否展示 uploadList, 可设为一个对象,用于单独设定 showPreviewIcon 和 showRemoveIcon | Boolean or { showPreviewIcon?: boolean, showRemoveIcon?: boolean } | true | |
supportServerRender | 服务端渲染时需要打开这个 | boolean | false | |
withCredentials | 上传请求时是否携带 cookie | boolean | false | |
openFileDialogOnClick | 点击打开文件对话框 | boolean | true | |
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 | 上传文件改变时的状态,详见 change | Function | 无 |
preview | 点击文件链接或预览图标时的回调 | Function(file) | 无 |
download | 点击下载文件时的回调,如果没有指定,则默认跳转到文件 url 对应的标签页。 | Function(file): void | 跳转新标签页 |
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 属性
xhr: 'XMLHttpRequest{ ... }', // XMLHttpRequest Header
}
fileList
当前的文件列表。event
上传中的服务端响应内容,包含了上传进度等信息,高级浏览器支持。