add upload

pull/165/head
wangxueliang 2018-04-13 16:19:50 +08:00
parent 25631cf541
commit 6933fce10d
26 changed files with 1876 additions and 5 deletions

View File

@ -116,6 +116,6 @@ export { default as Tooltip } from './tooltip'
// export { default as Mention } from './mention'
// export { default as Upload } from './upload'
export { default as Upload } from './upload'
export { default as version } from './version'

View File

@ -40,3 +40,4 @@ import './progress/style'
import './timeline/style'
import './input-number/style'
import './transfer/style'
import './upload/style'

View File

@ -148,7 +148,7 @@ export default {
render (h) {
const { $props, $data, $slots } = this
const { prefixCls, openClassName, getPopupContainer } = $props
const children = ($slots.default || []).filter(c => c.tag || c.text.trim() !== '')[0]
const children = ($slots.default || []).filter(c => c.tag || c.text.trim() !== '')
let sVisible = $data.sVisible
// Hide tooltip when there is no title
if (!hasProp(this, 'visible') && this.isNoTitle()) {

View File

@ -0,0 +1,20 @@
import { getOptionProps } from '../_util/props-util'
import Upload from './Upload'
import { UploadProps } from './interface'
export default {
name: 'ADragger',
props: UploadProps,
render () {
const props = getOptionProps(this)
const draggerProps = {
props: {
...props,
type: 'drag',
},
on: this.$listeners,
style: { height: this.height },
}
return <Upload {...draggerProps} >{this.$slots.default}</Upload>
},
}

View File

@ -0,0 +1,290 @@
import classNames from 'classnames'
import uniqBy from 'lodash/uniqBy'
import VcUpload from '../vc-upload'
import BaseMixin from '../_util/BaseMixin'
import { getOptionProps, initDefaultProps, hasProp } from '../_util/props-util'
import LocaleReceiver from '../locale-provider/LocaleReceiver'
import defaultLocale from '../locale-provider/default'
import Dragger from './Dragger'
import UploadList from './UploadList'
import { UploadProps } from './interface'
import { T, fileToObject, genPercentAdd, getFileItem, removeFileItem } from './utils'
export { UploadProps }
function noop () {}
export default {
name: 'AUpload',
Dragger: Dragger,
mixins: [BaseMixin],
props: initDefaultProps(UploadProps, {
prefixCls: 'ant-upload',
type: 'select',
multiple: false,
action: '',
data: {},
accept: '',
beforeUpload: T,
showUploadList: true,
listType: 'text', // or pictrue
disabled: false,
supportServerRender: true,
}),
// recentUploadStatus: boolean | PromiseLike<any>;
data () {
this.progressTimer = null
return {
sFileList: this.fileList || this.defaultFileList || [],
dragState: 'drop',
}
},
beforeDestroy () {
this.clearProgressTimer()
},
watch: {
fileList (val) {
this.sFileList = val
},
},
methods: {
onStart (file) {
const nextFileList = this.sFileList.concat()
const targetItem = fileToObject(file)
targetItem.status = 'uploading'
nextFileList.push(targetItem)
this.onChange({
file: targetItem,
fileList: nextFileList,
})
// fix ie progress
if (!window.FormData) {
this.autoUpdateProgress(0, targetItem)
}
},
autoUpdateProgress (_, file) {
const getPercent = genPercentAdd()
let curPercent = 0
this.clearProgressTimer()
this.progressTimer = setInterval(() => {
curPercent = getPercent(curPercent)
this.onProgress({
percent: curPercent,
}, file)
}, 200)
},
onSuccess (response, file) {
this.clearProgressTimer()
try {
if (typeof response === 'string') {
response = JSON.parse(response)
}
} catch (e) { /* do nothing */
}
const fileList = this.sFileList
const targetItem = getFileItem(file, fileList)
// removed
if (!targetItem) {
return
}
targetItem.status = 'done'
targetItem.response = response
this.onChange({
file: { ...targetItem },
fileList,
})
},
onProgress (e, file) {
const fileList = this.sFileList
const targetItem = getFileItem(file, fileList)
// removed
if (!targetItem) {
return
}
targetItem.percent = e.percent
this.onChange({
event: e,
file: { ...targetItem },
fileList: this.sFileList,
})
},
onError (error, response, file) {
this.clearProgressTimer()
const fileList = this.sFileList
const targetItem = getFileItem(file, fileList)
// removed
if (!targetItem) {
return
}
targetItem.error = error
targetItem.response = response
targetItem.status = 'error'
this.onChange({
file: { ...targetItem },
fileList,
})
},
handleRemove (file) {
Promise.resolve(this.$emit('remove', file)).then(ret => {
// Prevent removing file
if (ret === false) {
return
}
const removedFileList = removeFileItem(file, this.sFileList)
if (removedFileList) {
this.onChange({
file,
fileList: removedFileList,
})
}
})
},
handleManualRemove (file) {
this.$refs.uploadRef.abort(file)
file.status = 'removed' // eslint-disable-line
this.handleRemove(file)
},
onChange (info) {
if (!hasProp(this, 'fileList')) {
this.setState({ sFileList: info.fileList })
}
this.$emit('change', info)
},
onFileDrop (e) {
this.setState({
dragState: e.type,
})
},
reBeforeUpload (file, fileList) {
if (!this.beforeUpload) {
return true
}
const result = this.beforeUpload(file, fileList)
if (result === false) {
this.onChange({
file,
fileList: uniqBy(fileList.concat(this.sFileList), (item) => item.uid),
})
return false
} else if (result && result.then) {
return result
}
return true
},
clearProgressTimer () {
clearInterval(this.progressTimer)
},
renderUploadList (locale) {
const { showUploadList = {}, listType } = getOptionProps(this)
const { showRemoveIcon, showPreviewIcon } = showUploadList
const uploadListProps = {
props: {
listType,
items: this.sFileList,
showRemoveIcon,
showPreviewIcon,
locale: { ...locale, ...this.$props.locale },
},
on: {
remove: this.handleManualRemove,
preview: this.$listeners.preview || noop,
},
}
return (
<UploadList
{...uploadListProps}
/>
)
},
},
render () {
const {
prefixCls = '',
showUploadList,
listType,
type,
disabled,
} = getOptionProps(this)
const vcUploadProps = {
props: {
...this.$props,
beforeUpload: this.reBeforeUpload,
},
on: {
// ...this.$listeners,
start: this.onStart,
error: this.onError,
progress: this.onProgress,
success: this.onSuccess,
},
ref: 'uploadRef',
class: `${prefixCls}-btn`,
}
const uploadList = showUploadList ? (
<LocaleReceiver
componentName='Upload'
defaultLocale={defaultLocale.Upload}
children={this.renderUploadList}
>
</LocaleReceiver>
) : null
const children = this.$slots.default
if (type === 'drag') {
const dragCls = classNames(prefixCls, {
[`${prefixCls}-drag`]: true,
[`${prefixCls}-drag-uploading`]: this.sFileList.some(file => file.status === 'uploading'),
[`${prefixCls}-drag-hover`]: this.dragState === 'dragover',
[`${prefixCls}-disabled`]: disabled,
})
return (
<span>
<div
class={dragCls}
onDrop={this.onFileDrop}
onDragover={this.onFileDrop}
onDragleave={this.onFileDrop}
>
<VcUpload {...vcUploadProps}>
<div class={`${prefixCls}-drag-container`}>
{children}
</div>
</VcUpload>
</div>
{uploadList}
</span>
)
}
const uploadButtonCls = classNames(prefixCls, {
[`${prefixCls}-select`]: true,
[`${prefixCls}-select-${listType}`]: true,
[`${prefixCls}-disabled`]: disabled,
})
const uploadButton = (
<div class={uploadButtonCls} style={{ display: children ? '' : 'none' }}>
<VcUpload {...vcUploadProps} >{children}</VcUpload>
</div>
)
if (listType === 'picture-card') {
return (
<span>
{uploadList}
{uploadButton}
</span>
)
}
return (
<span>
{uploadButton}
{uploadList}
</span>
)
},
}

View File

@ -0,0 +1,222 @@
import BaseMixin from '../_util/BaseMixin'
import { getOptionProps, initDefaultProps } from '../_util/props-util'
import getTransitionProps from '../_util/getTransitionProps'
import Icon from '../icon'
import Tooltip from '../tooltip'
import Progress from '../progress'
import classNames from 'classnames'
import { UploadListProps } from './interface'
// https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
const previewFile = (file, callback) => {
const reader = new window.FileReader()
reader.onloadend = () => callback(reader.result)
reader.readAsDataURL(file)
}
const isImageUrl = (url) => {
return /^data:image\//.test(url) || /\.(webp|svg|png|gif|jpg|jpeg)$/.test(url)
}
export default {
name: 'AUploadList',
mixins: [BaseMixin],
props: initDefaultProps(UploadListProps, {
listType: 'text', // or picture
progressAttr: {
strokeWidth: 2,
showInfo: false,
},
prefixCls: 'ant-upload',
showRemoveIcon: true,
showPreviewIcon: true,
}),
updated () {
this.$nextTick(() => {
if (this.listType !== 'picture' && this.listType !== 'picture-card') {
return
}
(this.items || []).forEach(file => {
if (typeof document === 'undefined' ||
typeof window === 'undefined' ||
!window.FileReader || !window.File ||
!(file.originFileObj instanceof window.File) ||
file.thumbUrl !== undefined) {
return
}
/*eslint-disable */
file.thumbUrl = '';
/*eslint -enable */
previewFile(file.originFileObj, (previewDataUrl) => {
/*eslint-disable */
file.thumbUrl = previewDataUrl;
/*eslint -enable todo */
// this.forceUpdate()
})
})
})
},
methods: {
handleClose (file) {
this.$emit('remove', file)
},
handlePreview (file, e) {
e.preventDefault()
return this.$emit('preview', file)
},
},
render () {
const { prefixCls, items = [], listType, showPreviewIcon, showRemoveIcon, locale } = getOptionProps(this)
const list = items.map(file => {
let progress
let icon = <Icon type={file.status === 'uploading' ? 'loading' : 'paper-clip'} />
if (listType === 'picture' || listType === 'picture-card') {
if (listType === 'picture-card' && file.status === 'uploading') {
icon = <div class={`${prefixCls}-list-item-uploading-text`}>{locale.uploading}</div>
} else if (!file.thumbUrl && !file.url) {
icon = <Icon class={`${prefixCls}-list-item-thumbnail`} type='picture' />
} else {
const thumbnail = isImageUrl(file.thumbUrl || file.url) ? (
<img src={file.thumbUrl || file.url} alt={file.name} />
) : (
<Icon
type='file'
style={{ fontSize: '48px', color: 'rgba(0,0,0,0.5)' }}
/>
)
icon = (
<a
class={`${prefixCls}-list-item-thumbnail`}
onClick={e => this.handlePreview(file, e)}
href={file.url || file.thumbUrl}
target='_blank'
rel='noopener noreferrer'
>
{thumbnail}
</a>
)
}
}
if (file.status === 'uploading') {
const progressProps = {
props: {
...this.progressAttr,
type: 'line',
percent: file.percent,
}
}
// show loading icon if upload progress listener is disabled
const loadingProgress = ('percent' in file) ? (
<Progress {...progressProps} />
) : null
progress = (
<div class={`${prefixCls}-list-item-progress`} key='progress'>
{loadingProgress}
</div>
)
}
const infoUploadingClass = classNames({
[`${prefixCls}-list-item`]: true,
[`${prefixCls}-list-item-${file.status}`]: true,
})
const preview = file.url ? (
<a
{...file.linkProps}
href={file.url}
target='_blank'
rel='noopener noreferrer'
class={`${prefixCls}-list-item-name`}
onClick={e => this.handlePreview(file, e)}
title={file.name}
>
{file.name}
</a>
) : (
<span
class={`${prefixCls}-list-item-name`}
onClick={e => this.handlePreview(file, e)}
title={file.name}
>
{file.name}
</span>
)
const style = (file.url || file.thumbUrl) ? undefined : {
pointerEvents: 'none',
opacity: 0.5,
}
const previewIcon = showPreviewIcon ? (
<a
href={file.url || file.thumbUrl}
target='_blank'
rel='noopener noreferrer'
style={style}
onClick={e => this.handlePreview(file, e)}
title={locale.previewFile}
>
<Icon type='eye-o' />
</a>
) : null
const iconProps = {
props: {
type: 'delete',
title: locale.removeFile,
},
on: {
click: () => {
this.handleClose(file)
}
},
}
const iconProps1 = {...iconProps, ...{props: {type: 'cross'}}}
const removeIcon = showRemoveIcon ? (
<Icon {...iconProps} />
) : null
const removeIconCross = showRemoveIcon ? (
<Icon {...iconProps1}/>
) : null
const actions = (listType === 'picture-card' && file.status !== 'uploading')
? <span class={`${prefixCls}-list-item-actions`}>{previewIcon}{removeIcon}</span>
: removeIconCross
let message
if (file.response && typeof file.response === 'string') {
message = file.response
} else {
message = (file.error && file.error.statusText) || locale.uploadError
}
const iconAndPreview = (file.status === 'error')
? <Tooltip title={message}>{icon}{preview}</Tooltip>
: <span>{icon}{preview}</span>
const transitionProps = getTransitionProps('fade')
return (
<div class={infoUploadingClass} key={file.uid}>
<div class={`${prefixCls}-list-item-info`}>
{iconAndPreview}
</div>
{actions}
<transition {...transitionProps}>
{progress}
</transition>
</div>
)
})
const listClassNames = classNames({
[`${prefixCls}-list`]: true,
[`${prefixCls}-list-${listType}`]: true,
})
const animationDirection =
listType === 'picture-card' ? 'animate-inline' : 'animate'
const transitionGroupProps = getTransitionProps(`${prefixCls}-${animationDirection}`)
return (
<transition-group
{...transitionGroupProps}
tag='div'
class={listClassNames}
>
{list}
</transition-group>
)
},
}

View File

@ -0,0 +1,80 @@
<cn>
#### 用户头像
点击上传用户头像,并使用 `beforeUpload` 限制用户上传的图片格式和大小。
`beforeUpload` 的返回值可以是一个 Promise 以支持也支持异步检查
</cn>
<us>
#### Avatar
Click to upload user's avatar, and validate size and format of picture with `beforeUpload`.
The return value of function `beforeUpload` can be a Promise to check asynchronously.
</us>
```html
<template>
<a-upload
name="avatar"
listType="picture-card"
class="avatar-uploader"
:showUploadList="false"
action="//jsonplaceholder.typicode.com/posts/"
:beforeUpload="beforeUpload"
@change="handleChange"
>
<img v-if="imageUrl" :src="imageUrl" alt="" />
<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 isJPG = file.type === 'image/jpeg';
if (!isJPG) {
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 isJPG && isLt2M;
},
},
}
</script>
<style scoped>
.avatar-uploader > .ant-upload {
width: 128px;
height: 128px;
}
</style>
```

View File

@ -0,0 +1,43 @@
<cn>
#### 点击上传
经典款式,用户点击按钮弹出文件选择框。
</cn>
<us>
#### Upload by clicking
Classic mode. File selection dialog pops up when upload button is clicked.
</us>
```html
<template>
<a-upload name="file" action="//jsonplaceholder.typicode.com/posts/" :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>
```

View File

@ -0,0 +1,54 @@
<cn>
#### 已上传的文件列表
使用 `defaultFileList` 设置已上传的内容。
</cn>
<us>
#### Default Files
Use `defaultFileList` for uploaded files when page init.
</us>
```html
<template>
<a-upload action="//jsonplaceholder.typicode.com/posts/" :defaultFileList="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',
reponse: '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',
reponse: '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>
```

View File

@ -0,0 +1,44 @@
<cn>
#### 拖拽上传
把文件拖入指定区域,完成上传,同样支持点击上传。
设置 `multiple` 后,在 `IE10+` 可以一次上传多个文件。
</cn>
<us>
#### Drag and Drop
Classic mode. File selection dialog pops up when upload button is clicked.
</us>
```html
<template>
<a-dragger name="file" :multiple="true" action="//jsonplaceholder.typicode.com/posts/" @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-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>
```

View File

@ -0,0 +1,69 @@
<cn>
#### 完全控制的上传列表
使用 `fileList` 对列表进行完全控制,可以实现各种自定义功能,以下演示三种情况:
1) 上传列表数量的限制。
2) 读取远程路径并显示链接。
3) 按照服务器返回信息筛选成功上传的文件。
</cn>
<us>
#### Complete control over file list
You can gain full control over filelist by configuring `fileList`. You can accomplish all kinds of customed functions. The following shows three circumstances:
1) limit the number of uploaded files.
2) read from response and show file link.
3) filter successfully uploaded files according to response from server.
</us>
```html
<template>
<a-upload action="//jsonplaceholder.typicode.com/posts/" :multiple="true" :fileList="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;
});
// 3. filter successfully uploaded files according to response from server
fileList = fileList.filter((file) => {
if (file.response) {
return file.response.status === 'success';
}
return true;
});
this.fileList = fileList
},
},
}
</script>
```

View File

@ -0,0 +1,71 @@
<script>
import Basic from './basic.md'
import Avatar from './avatar.md'
import DefaultFileList from './defaultFileList.md'
import PictureCard from './picture-card.md'
import FileList from './fileList.md'
import Drag from './drag.md'
import PictureStyle from './picture-style.md'
import UploadManually from './upload-manually.md'
import CN from '../index.zh-CN.md'
import US from '../index.en-US.md'
const md = {
cn: `# 上传
上传是将信息网页文字图片视频等通过网页或者上传工具发布到远程服务器上的过程
## 何时使用
- 当需要上传一个或一些文件时
- 当需要展现上传的进度时
- 当需要使用拖拽交互时
## 代码演示`,
us: `# Upload
Upload file by selecting or dragging.
## When To Use
Uploading is the process of publishing information (web pages, text, pictures, video, etc.) to a remote server via a web page or upload tool.
- When you need to upload one or more files.
- When you need to show the process of uploading.
- When you need to upload files by dragging and dropping.
## Examples
`,
}
export default {
category: 'Components',
subtitle: '上传',
type: 'Data Entry',
title: 'Upload',
render () {
return (
<div>
<md cn={md.cn} us={md.us}/>
<br/>
<Basic />
<br/>
<Avatar />
<br />
<DefaultFileList />
<br/>
<PictureCard />
<br/>
<FileList />
<br/>
<Drag />
<br/>
<PictureStyle />
<br/>
<UploadManually />
<br/>
<api>
<template slot='cn'>
<CN/>
</template>
<US/>
</api>
</div>
)
},
}
</script>

View File

@ -0,0 +1,73 @@
<cn>
#### 照片墙
用户可以上传图片并在列表中显示缩略图。当上传照片数到达限制后,上传按钮消失。
</cn>
<us>
#### Pictures Wall
After users upload picture, the thumbnail will be shown in list. The upload button will disappear when count meets limitation.
</us>
```html
<template>
<div class="clearfix">
<a-upload
action="//jsonplaceholder.typicode.com/posts/"
listType="picture-card"
:fileList="fileList"
@preview="handlePreview"
@change="handleChange"
>
<div v-if="fileList.length < 3">
<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>
export default {
data () {
return {
previewVisible: false,
previewImage: '',
fileList: [{
uid: -1,
name: 'xxx.png',
status: 'done',
url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
}],
}
},
methods: {
handleCancel() {
this.previewVisible = false
},
handlePreview(file) {
this.previewImage = file.url || file.thumbUrl
this.previewVisible = true
},
handleChange({ fileList }) {
this.fileList = fileList
},
},
}
</script>
<style scoped>
/* 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>
```

View File

@ -0,0 +1,75 @@
<cn>
#### 图片列表样式
上传文件为图片,可展示本地缩略图。`IE8/9` 不支持浏览器本地缩略图展示([Ref](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL)),可以写 `thumbUrl` 属性来代替。
</cn>
<us>
#### Pictures with list style
If uploaded file is a picture, the thumbnail can be shown. `IE8/9` do not support local thumbnail show. Please use `thumbUrl` instead.
</us>
```html
<template>
<div>
<a-upload
action="//jsonplaceholder.typicode.com/posts/"
listType="picture-card"
:defaultFileList="fileList"
>
<a-button>
<a-icon type="upload" /> upload
</a-button>
</a-upload>
<br />
<br />
<a-upload
action="//jsonplaceholder.typicode.com/posts/"
listType="picture"
:defaultFileList="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>
```

View File

@ -0,0 +1,91 @@
<cn>
#### 手动上传
`beforeUpload` 返回 `false` 后,手动上传文件。
</cn>
<us>
#### Upload manually
Upload files manually after `beforeUpload` returns `false`.
</us>
```html
<template>
<div class="clearfix">
<a-upload
action="//jsonplaceholder.typicode.com/posts/"
:fileList="fileList"
@remove="handleRemove"
:beforeUpload="beforeUpload"
>
<a-button>
<a-icon type="upload" /> Select File
</a-button>
</a-upload>
<a-button
class="upload-demo-start"
type="primary"
@click="handleUpload"
:disabled="fileList.length === 0"
:loading="uploading"
>
{{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: '//jsonplaceholder.typicode.com/posts/',
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>
<style scoped>
.upload-demo-start {
margin-top: 16px;
}
</style>
```

View File

@ -0,0 +1,58 @@
## API
> You can consult [jQuery-File-Upload](https://github.com/blueimp/jQuery-File-Upload/wiki) about how to implement server side upload interface.
| Property | Description | Type | Default |
| -------- | ----------- | ---- | ------- |
| accept | File types that can be accepted. See [input accept Attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-accept) | string | - |
| action | Required. Uploading URL | string | - |
| beforeUpload | Hook function which will be executed before uploading. Uploading will be stopped with `false` or a rejected Promise returned. **Warningthis function is not supported in IE9**。 | (file, fileList) => `boolean | Promise` | - |
| customRequest | override for the default xhr behavior allowing for additional customization and ability to implement your own XMLHttpRequest | Function | - |
| data | Uploading params or function which can return uploading params. | object\|function(file) | - |
| defaultFileList | Default list of files that have been uploaded. | object\[] | - |
| disabled | disable upload button | boolean | false |
| fileList | List of files that have been uploaded (controlled). Here is a common issue [#2423](https://github.com/ant-design/ant-design/issues/2423) when using it | object\[] | - |
| headers | Set request headers, valid above IE10. | object | - |
| listType | Built-in stylesheets, support for three types: `text`, `picture` or `picture-card` | string | 'text' |
| multiple | Whether to support selected multiple file. `IE10+` supported. You can select multiple files with CTRL holding down while multiple is set to be true | boolean | false |
| name | The name of uploading file | string | 'file' |
| showUploadList | Whether to show default upload list, could be an object to specify `showPreviewIcon` and `showRemoveIcon` individually | Boolean or { showPreviewIcon?: boolean, showRemoveIcon?: boolean } | true |
| supportServerRender | Need to be turned on while the server side is rendering. | boolean | false |
| withCredentials | ajax upload with cookie sent | boolean | false |
### events
| Events Name | Description | Arguments |
| --- | --- | --- |
| change | A callback function, can be executed when uploading state is changing. See [change](#change) | Function | - |
| preview | A callback function, will be executed when file link or preview icon is clicked. | Function(file) | - |
| remove | A callback function, will be executed when removing file button is clicked, remove event will be prevented when return value is `false` or a Promise which resolve(false) or reject. | Function(file): `boolean | Promise` | - |
### change
> The function will be called when uploading is in progress, completed or failed
When uploading state change, it returns:
```js
{
file: { /* ... */ },
fileList: [ /* ... */ ],
event: { /* ... */ },
}
```
1. `file` File object for the current operation.
```js
{
uid: 'uid', // unique identifiernegative is recommendto prevent interference with internal generated id
name: 'xx.png' // file name
status: 'done', // optionsuploading, done, error, removed
response: '{"status": "success"}', // response from server
linkProps: '{"download": "image"}', // additional html props of file link
}
```
2. `fileList` current list of files
3. `event` response from server, including uploading progress, supported by advanced browsers.

View File

@ -0,0 +1,8 @@
import Upload from './Upload'
import Dragger from './Dragger'
export { UploadProps, UploadListProps, UploadChangeParam } from './interface'
export { DraggerProps } from './Dragger'
Upload.Dragger = Dragger
export default Upload

View File

@ -0,0 +1,57 @@
## API
> 服务端上传接口实现可以参考 [jQuery-File-Upload](https://github.com/blueimp/jQuery-File-Upload/wiki)。
| 参数 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| accept | 接受上传的文件类型, 详见 [input accept Attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-accept) | string | 无 |
| action | 必选参数, 上传的地址 | string | 无 |
| beforeUpload | 上传文件之前的钩子,参数为上传的文件,若返回 `false` 则停止上传。支持返回一个 Promise 对象Promise 对象 reject 时则停止上传resolve 时开始上传。**注意IE9 不支持该方法**。 | (file, fileList) => `boolean | Promise` | 无 |
| customRequest | 通过覆盖默认的上传行为,可以自定义自己的上传实现 | Function | 无 |
| data | 上传所需参数或返回上传参数的方法 | object\|function(file) | 无 |
| 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' |
| showUploadList | 是否展示 uploadList, 可设为一个对象,用于单独设定 showPreviewIcon 和 showRemoveIcon | Boolean or { showPreviewIcon?: boolean, showRemoveIcon?: boolean } | true |
| supportServerRender | 服务端渲染时需要打开这个 | boolean | false |
| withCredentials | 上传请求时是否携带 cookie | boolean | false |
### 事件
| 事件名称 | 说明 | 回调参数 |
| --- | --- | --- |
| change | 上传文件改变时的状态,详见 [change](#change) | Function | 无 |
| preview | 点击文件链接或预览图标时的回调 | Function(file) | 无 |
| remove   | 点击移除文件时的回调,返回值为 false 时不移除。支持返回一个 Promise 对象Promise 对象 resolve(false) 或 reject 时不移除。               | Function(file): `boolean | Promise` | 无   |
### change
> 上传中、完成、失败都会调用这个函数。
文件状态改变的回调,返回为:
```js
{
file: { /* ... */ },
fileList: [ /* ... */ ],
event: { /* ... */ },
}
```
1. `file` 当前操作的文件对象。
```js
{
uid: 'uid', // 文件唯一标识,建议设置为负数,防止和内部产生的 id 冲突
name: 'xx.png' // 文件名
status: 'done', // 状态有uploading done error removed
response: '{"status": "success"}', // 服务端响应内容
linkProps: '{"download": "image"}', // 下载链接额外的 HTML 属性
}
```
2. `fileList` 当前的文件列表。
3. `event` 上传中的服务端响应内容,包含了上传进度等信息,高级浏览器支持。

90
components/upload/interface.jsx Executable file
View File

@ -0,0 +1,90 @@
import PropsTypes from '../_util/vue-types'
export const UploadFileStatus = PropsTypes.oneOf(['error', 'success', 'done', 'uploading', 'removed'])
// export const HttpRequestHeader {
// [key: string]: string;
// }
export const UploadFile = PropsTypes.shape({
uid: PropsTypes.oneOfType([
PropsTypes.string,
PropsTypes.number,
]),
size: PropsTypes.number,
name: PropsTypes.string,
filename: PropsTypes.string,
lastModified: PropsTypes.number,
lastModifiedDate: PropsTypes.any,
url: PropsTypes.string,
status: UploadFileStatus,
percent: PropsTypes.number,
thumbUrl: PropsTypes.string,
originFileObj: PropsTypes.any,
response: PropsTypes.any,
error: PropsTypes.any,
linkProps: PropsTypes.any,
type: PropsTypes.string,
}).loose
export const UploadChangeParam = {
file: UploadFile,
fileList: PropsTypes.arrayOf(UploadFile),
event: PropsTypes.object,
}
export const ShowUploadListInterface = PropsTypes.shape({
showRemoveIcon: PropsTypes.bool,
showPreviewIcon: PropsTypes.bool,
}).loose
export const UploadLocale = PropsTypes.shape({
uploading: PropsTypes.string,
removeFile: PropsTypes.string,
uploadError: PropsTypes.string,
previewFile: PropsTypes.string,
}).loose
export const UploadProps = {
type: PropsTypes.oneOf(['drag', 'select']),
name: PropsTypes.string,
defaultFileList: PropsTypes.arrayOf(UploadFile),
fileList: PropsTypes.arrayOf(UploadFile),
action: PropsTypes.string.isRequired,
data: PropsTypes.oneOfType([PropsTypes.object, PropsTypes.func]),
headers: PropsTypes.object,
showUploadList: PropsTypes.oneOfType([PropsTypes.bool, ShowUploadListInterface]),
multiple: PropsTypes.bool,
accept: PropsTypes.string,
beforeUpload: PropsTypes.func,
// onChange: PropsTypes.func,
listType: PropsTypes.oneOf(['text', 'picture', 'picture-card']),
// className: PropsTypes.string,
// onPreview: PropsTypes.func,
// onRemove: PropsTypes.func,
supportServerRender: PropsTypes.bool,
// style: PropsTypes.object,
disabled: PropsTypes.bool,
prefixCls: PropsTypes.string,
customRequest: PropsTypes.func,
withCredentials: PropsTypes.bool,
locale: UploadLocale,
height: PropsTypes.number,
}
export const UploadState = {
fileList: PropsTypes.arrayOf(UploadFile),
dragState: PropsTypes.string,
}
export const UploadListProps = {
listType: PropsTypes.oneOf(['text', 'picture', 'picture-card']),
// onPreview: PropsTypes.func,
// onRemove: PropsTypes.func,
items: PropsTypes.arrayOf(UploadFile),
// items: PropsTypes.any,
progressAttr: PropsTypes.object,
prefixCls: PropsTypes.string,
showRemoveIcon: PropsTypes.bool,
showPreviewIcon: PropsTypes.bool,
locale: UploadLocale,
}

View File

@ -0,0 +1,6 @@
import '../../style/index.less'
import './index.less'
// style dependencies
import '../../progress/style'
import '../../tooltip/style'

View File

@ -0,0 +1,459 @@
@import "../../style/themes/default";
@import "../../style/mixins/index";
@upload-prefix-cls: ~"@{ant-prefix}-upload";
@upload-item: ~"@{ant-prefix}-upload-list-item";
@upload-pictrue-card-size: 104px;
.@{upload-prefix-cls} {
.reset-component;
outline: 0;
p {
margin: 0;
}
&-btn {
display: block;
width: 100%;
outline: none;
}
input[type="file"] {
cursor: pointer;
}
&&-select {
display: inline-block;
}
&&-select-picture-card {
border: @border-width-base dashed @border-color-base;
width: @upload-pictrue-card-size;
height: @upload-pictrue-card-size;
border-radius: @border-radius-base;
background-color: @background-color-light;
text-align: center;
cursor: pointer;
transition: border-color 0.3s ease;
vertical-align: top;
margin-right: 8px;
margin-bottom: 8px;
display: table;
> .@{upload-prefix-cls} {
width: 100%;
height: 100%;
display: table-cell;
text-align: center;
vertical-align: middle;
padding: 8px;
}
&:hover {
border-color: @primary-color;
}
}
&&-drag {
border: @border-width-base dashed @border-color-base;
transition: border-color .3s;
cursor: pointer;
border-radius: @border-radius-base;
text-align: center;
width: 100%;
height: 100%;
position: relative;
padding: 16px 0;
background: @background-color-light;
&.@{upload-prefix-cls}-drag-hover:not(.@{upload-prefix-cls}-disabled) {
border: 2px dashed @primary-5;
}
&.@{upload-prefix-cls}-disabled {
cursor: not-allowed;
}
.@{upload-prefix-cls}-btn {
display: table;
height: 100%;
}
.@{upload-prefix-cls}-drag-container {
display: table-cell;
vertical-align: middle;
}
&:not(.@{upload-prefix-cls}-disabled):hover {
border-color: @primary-5;
}
p.@{upload-prefix-cls}-drag-icon {
.@{iconfont-css-prefix} {
font-size: 48px;
color: @primary-5;
}
margin-bottom: 20px;
}
p.@{upload-prefix-cls}-text {
font-size: @font-size-lg;
margin: 0 0 4px;
color: @heading-color;
}
p.@{upload-prefix-cls}-hint {
font-size: @font-size-base;
color: @text-color-secondary;
}
.@{iconfont-css-prefix}-plus {
font-size: 30px;
transition: all .3s;
color: @disabled-color;
&:hover {
color: @text-color-secondary;
}
}
&:hover .@{iconfont-css-prefix}-plus {
color: @text-color-secondary;
}
}
}
.@{upload-prefix-cls}-list {
.reset-component;
.clearfix;
&-item {
margin-top: 8px;
font-size: @font-size-base;
position: relative;
height: 22px;
&-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding-left: @font-size-base + 8px;
width: 100%;
display: inline-block;
}
&-info {
height: 100%;
padding: 0 12px 0 4px;
transition: background-color .3s;
> span {
display: block;
}
.@{iconfont-css-prefix}-loading,
.@{iconfont-css-prefix}-paper-clip {
font-size: @font-size-base;
color: @text-color-secondary;
position: absolute;
top: @font-size-base / 2 - 2px;
}
}
.@{iconfont-css-prefix}-cross {
.iconfont-size-under-12px(10px);
transition: all .3s;
opacity: 0;
cursor: pointer;
position: absolute;
top: 0;
right: 4px;
color: @text-color-secondary;
line-height: 22px;
&:hover {
color: @text-color;
}
}
&:hover &-info {
background-color: @item-hover-bg;
}
&:hover .@{iconfont-css-prefix}-cross {
opacity: 1;
}
&-error,
&-error .@{iconfont-css-prefix}-paper-clip,
&-error &-name {
color: @error-color;
}
&-error .@{iconfont-css-prefix}-cross {
opacity: 1;
color: @error-color !important;
}
&-progress {
line-height: 0;
font-size: @font-size-base;
position: absolute;
width: 100%;
bottom: -12px;
padding-left: @font-size-base + 12px;
}
}
&-picture,
&-picture-card {
.@{upload-item} {
padding: 8px;
border-radius: @border-radius-base;
border: @border-width-base @border-style-base @border-color-base;
height: 66px;
position: relative;
&:hover {
background: transparent;
}
&-error {
border-color: @error-color;
}
}
.@{upload-item}-info {
padding: 0;
}
.@{upload-item}:hover .@{upload-item}-info {
background: transparent;
}
.@{upload-item}-uploading {
border-style: dashed;
}
.@{upload-item}-thumbnail {
width: 48px;
height: 48px;
position: absolute;
top: 8px;
left: 8px;
}
.@{upload-item}-thumbnail img {
width: 48px;
height: 48px;
display: block;
overflow: hidden;
}
.@{upload-item}-thumbnail.@{iconfont-css-prefix}:before {
line-height: 48px;
font-size: 24px;
color: @text-color-secondary;
}
.@{upload-item}-name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin: 0 0 0 8px;
line-height: 44px;
transition: all .3s;
padding-left: 48px;
padding-right: 8px;
max-width: 100%;
display: inline-block;
box-sizing: border-box;
}
.@{upload-item}-uploading .@{upload-item}-name {
line-height: 28px;
}
.@{upload-item}-progress {
padding-left: 56px;
margin-top: 0;
bottom: 14px;
width: ~"calc(100% - 24px)";
}
.@{iconfont-css-prefix}-cross {
position: absolute;
right: 8px;
top: 8px;
line-height: 1;
}
}
&-picture-card {
display: inline;
&.@{upload-prefix-cls}-list:after {
display: none;
}
.@{upload-item} {
float: left;
width: @upload-pictrue-card-size;
height: @upload-pictrue-card-size;
margin: 0 8px 8px 0;
}
.@{upload-item}-info {
height: 100%;
position: relative;
overflow: hidden;
&:before {
content: ' ';
position: absolute;
z-index: 1;
background-color: rgba(0, 0, 0, 0.5);
transition: all .3s;
width: 100%;
height: 100%;
opacity: 0;
}
}
.@{upload-item}:hover .@{upload-item}-info:before {
opacity: 1;
}
.@{upload-item}-actions {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
z-index: 10;
white-space: nowrap;
opacity: 0;
transition: all .3s;
.@{iconfont-css-prefix}-eye-o,
.@{iconfont-css-prefix}-delete {
z-index: 10;
transition: all .3s;
cursor: pointer;
font-size: 16px;
width: 16px;
color: @text-color-dark;
margin: 0 4px;
&:hover {
color: #fff;
}
}
}
.@{upload-item}-info:hover + .@{upload-item}-actions,
.@{upload-item}-actions:hover {
opacity: 1;
}
.@{upload-item}-thumbnail,
.@{upload-item}-thumbnail img {
display: block;
width: 100%;
height: 100%;
position: static;
}
.@{upload-item}-name {
margin: 8px 0 0;
padding: 0;
text-align: center;
line-height: @line-height-base;
display: none;
}
.anticon-picture + .@{upload-item}-name {
display: block;
}
.@{upload-item}-uploading {
&.@{upload-item} {
background-color: @background-color-light;
}
.@{upload-item}-info {
height: auto;
&:before,
.@{iconfont-css-prefix}-eye-o,
.@{iconfont-css-prefix}-delete {
display: none;
}
}
&-text {
margin-top: 18px;
color: @text-color-secondary;
}
}
.@{upload-item}-progress {
padding-left: 0;
bottom: 32px;
}
}
.@{upload-prefix-cls}-success-icon {
color: @success-color;
font-weight: bold;
}
.@{upload-prefix-cls}-animate-enter,
.@{upload-prefix-cls}-animate-leave,
.@{upload-prefix-cls}-animate-inline-enter,
.@{upload-prefix-cls}-animate-inline-leave {
animation-duration: .3s;
animation-fill-mode: @ease-in-out-circ;
}
.@{upload-prefix-cls}-animate-enter {
animation-name: uploadAnimateIn;
}
.@{upload-prefix-cls}-animate-leave {
animation-name: uploadAnimateOut;
}
.@{upload-prefix-cls}-animate-inline-enter {
animation-name: uploadAnimateInlineIn;
}
.@{upload-prefix-cls}-animate-inline-leave {
animation-name: uploadAnimateInlineOut;
}
}
@keyframes uploadAnimateIn {
from {
height: 0;
margin: 0;
opacity: 0;
padding: 0;
}
}
@keyframes uploadAnimateOut {
to {
height: 0;
margin: 0;
padding: 0;
opacity: 0;
}
}
@keyframes uploadAnimateInlineIn {
from {
width: 0;
height: 0;
margin: 0;
opacity: 0;
padding: 0;
}
}
@keyframes uploadAnimateInlineOut {
to {
width: 0;
height: 0;
margin: 0;
padding: 0;
opacity: 0;
}
}

View File

@ -0,0 +1,57 @@
export function T () {
return true
}
// Fix IE file.status problem
// via coping a new Object
export function fileToObject (file) {
return {
lastModified: file.lastModified,
lastModifiedDate: file.lastModifiedDate,
name: file.filename || file.name,
size: file.size,
type: file.type,
uid: file.uid,
response: file.response,
error: file.error,
percent: 0,
originFileObj: file,
}
}
/**
* 生成Progress percent: 0.1 -> 0.98
* - for ie
*/
export function genPercentAdd () {
let k = 0.1
const i = 0.01
const end = 0.98
return function (s) {
let start = s
if (start >= end) {
return start
}
start += k
k = k - i
if (k < 0.001) {
k = 0.001
}
return start * 100
}
}
export function getFileItem (file, fileList) {
const matchKey = file.uid !== undefined ? 'uid' : 'name'
return fileList.filter(item => item[matchKey] === file[matchKey])[0]
}
export function removeFileItem (file, fileList) {
const matchKey = file.uid !== undefined ? 'uid' : 'name'
const removed = fileList.filter(item => item[matchKey] !== file[matchKey])
if (removed.length === fileList.length) {
return null
}
return removed
}

View File

@ -143,6 +143,7 @@
"lodash": "^4.17.5",
"moment": "^2.21.0",
"omit.js": "^1.0.0",
"reqwest": "^2.0.5",
"shallow-equal": "^1.0.0",
"shallowequal": "^1.0.2",
"vue": "^2.5.15",

View File

@ -52,7 +52,7 @@ import {
Timeline,
Tooltip,
// Mention,
// Upload,
Upload,
// version,
} from 'antd'
@ -133,7 +133,8 @@ Vue.component(Timeline.name, Timeline)
Vue.component(Timeline.Item.name, Timeline.Item)
Vue.component(Tooltip.name, Tooltip)
// Vue.component(Mention.name, Mention)
// Vue.component(Upload.name, Upload)
Vue.component(Upload.name, Upload)
Vue.component(Upload.Dragger.name, Upload.Dragger)
Vue.prototype.$message = message
Vue.prototype.$notification = notification

View File

@ -41,3 +41,4 @@ export { default as timeline } from 'antd/timeline/demo/index.vue'
export { default as table } from 'antd/table/demo/index.vue'
export { default as inputNumber } from 'antd/input-number/demo/index.vue'
export { default as transfer } from 'antd/transfer/demo/index.vue'
export { default as upload } from 'antd/upload/demo/index.vue'

View File

@ -3,7 +3,7 @@ import Layout from './components/layout.vue'
const AsyncTestComp = () => {
const d = window.location.hash.replace('#', '')
return {
component: import(`../components/vc-upload/demo/${d}`),
component: import(`../components/upload/demo/${d}`),
}
}