From b20dd5156248fc22fba56022584eca9fa8621a0a Mon Sep 17 00:00:00 2001 From: wangxueliang Date: Fri, 13 Apr 2018 16:19:50 +0800 Subject: [PATCH] add upload --- components/index.js | 2 +- components/style.js | 1 + components/tooltip/Tooltip.jsx | 2 +- components/upload/Dragger.jsx | 20 + components/upload/Upload.jsx | 290 ++++++++++++++ components/upload/UploadList.jsx | 222 +++++++++++ components/upload/demo/avatar.md | 80 ++++ components/upload/demo/basic.md | 43 ++ components/upload/demo/defaultFileList.md | 54 +++ components/upload/demo/drag.md | 44 +++ components/upload/demo/fileList.md | 69 ++++ components/upload/demo/index.vue | 71 ++++ components/upload/demo/picture-card.md | 73 ++++ components/upload/demo/picture-style.md | 75 ++++ components/upload/demo/upload-manually.md | 91 +++++ components/upload/index.en-US.md | 58 +++ components/upload/index.jsx | 8 + components/upload/index.zh-CN.md | 57 +++ components/upload/interface.jsx | 90 +++++ components/upload/style/index.jsx | 6 + components/upload/style/index.less | 459 ++++++++++++++++++++++ components/upload/utils.jsx | 57 +++ package.json | 1 + site/components.js | 5 +- site/demo.js | 1 + site/routes.js | 2 +- 26 files changed, 1876 insertions(+), 5 deletions(-) create mode 100644 components/upload/Dragger.jsx create mode 100644 components/upload/Upload.jsx create mode 100644 components/upload/UploadList.jsx create mode 100644 components/upload/demo/avatar.md create mode 100644 components/upload/demo/basic.md create mode 100644 components/upload/demo/defaultFileList.md create mode 100644 components/upload/demo/drag.md create mode 100644 components/upload/demo/fileList.md create mode 100644 components/upload/demo/index.vue create mode 100644 components/upload/demo/picture-card.md create mode 100644 components/upload/demo/picture-style.md create mode 100644 components/upload/demo/upload-manually.md create mode 100644 components/upload/index.en-US.md create mode 100644 components/upload/index.jsx create mode 100644 components/upload/index.zh-CN.md create mode 100755 components/upload/interface.jsx create mode 100644 components/upload/style/index.jsx create mode 100644 components/upload/style/index.less create mode 100644 components/upload/utils.jsx diff --git a/components/index.js b/components/index.js index 145b1ab51..cda73efde 100644 --- a/components/index.js +++ b/components/index.js @@ -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' diff --git a/components/style.js b/components/style.js index 8f24af65c..22e6acc78 100644 --- a/components/style.js +++ b/components/style.js @@ -40,3 +40,4 @@ import './progress/style' import './timeline/style' import './input-number/style' import './transfer/style' +import './upload/style' diff --git a/components/tooltip/Tooltip.jsx b/components/tooltip/Tooltip.jsx index 8a582985a..b2315326b 100644 --- a/components/tooltip/Tooltip.jsx +++ b/components/tooltip/Tooltip.jsx @@ -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()) { diff --git a/components/upload/Dragger.jsx b/components/upload/Dragger.jsx new file mode 100644 index 000000000..88ffd693e --- /dev/null +++ b/components/upload/Dragger.jsx @@ -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 {this.$slots.default} + }, +} diff --git a/components/upload/Upload.jsx b/components/upload/Upload.jsx new file mode 100644 index 000000000..1cb8e2d54 --- /dev/null +++ b/components/upload/Upload.jsx @@ -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; + 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 ( + + ) + }, + }, + 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 ? ( + + + ) : 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 ( + +
+ +
+ {children} +
+
+
+ {uploadList} +
+ ) + } + + const uploadButtonCls = classNames(prefixCls, { + [`${prefixCls}-select`]: true, + [`${prefixCls}-select-${listType}`]: true, + [`${prefixCls}-disabled`]: disabled, + }) + const uploadButton = ( +
+ {children} +
+ ) + + if (listType === 'picture-card') { + return ( + + {uploadList} + {uploadButton} + + ) + } + return ( + + {uploadButton} + {uploadList} + + ) + }, +} diff --git a/components/upload/UploadList.jsx b/components/upload/UploadList.jsx new file mode 100644 index 000000000..cda161c3a --- /dev/null +++ b/components/upload/UploadList.jsx @@ -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 = + + if (listType === 'picture' || listType === 'picture-card') { + if (listType === 'picture-card' && file.status === 'uploading') { + icon =
{locale.uploading}
+ } else if (!file.thumbUrl && !file.url) { + icon = + } else { + const thumbnail = isImageUrl(file.thumbUrl || file.url) ? ( + {file.name} + ) : ( + + ) + icon = ( + this.handlePreview(file, e)} + href={file.url || file.thumbUrl} + target='_blank' + rel='noopener noreferrer' + > + {thumbnail} + + ) + } + } + + 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) ? ( + + ) : null + + progress = ( +
+ {loadingProgress} +
+ ) + } + const infoUploadingClass = classNames({ + [`${prefixCls}-list-item`]: true, + [`${prefixCls}-list-item-${file.status}`]: true, + }) + const preview = file.url ? ( + this.handlePreview(file, e)} + title={file.name} + > + {file.name} + + ) : ( + this.handlePreview(file, e)} + title={file.name} + > + {file.name} + + ) + const style = (file.url || file.thumbUrl) ? undefined : { + pointerEvents: 'none', + opacity: 0.5, + } + const previewIcon = showPreviewIcon ? ( + this.handlePreview(file, e)} + title={locale.previewFile} + > + + + ) : null + const iconProps = { + props: { + type: 'delete', + title: locale.removeFile, + }, + on: { + click: () => { + this.handleClose(file) + } + }, + } + const iconProps1 = {...iconProps, ...{props: {type: 'cross'}}} + const removeIcon = showRemoveIcon ? ( + + ) : null + const removeIconCross = showRemoveIcon ? ( + + ) : null + const actions = (listType === 'picture-card' && file.status !== 'uploading') + ? {previewIcon}{removeIcon} + : 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') + ? {icon}{preview} + : {icon}{preview} + const transitionProps = getTransitionProps('fade') + return ( +
+
+ {iconAndPreview} +
+ {actions} + + {progress} + +
+ ) + }) + const listClassNames = classNames({ + [`${prefixCls}-list`]: true, + [`${prefixCls}-list-${listType}`]: true, + }) + const animationDirection = + listType === 'picture-card' ? 'animate-inline' : 'animate' + const transitionGroupProps = getTransitionProps(`${prefixCls}-${animationDirection}`) + return ( + + {list} + + ) + }, +} diff --git a/components/upload/demo/avatar.md b/components/upload/demo/avatar.md new file mode 100644 index 000000000..7041bf90b --- /dev/null +++ b/components/upload/demo/avatar.md @@ -0,0 +1,80 @@ + +#### 用户头像 +点击上传用户头像,并使用 `beforeUpload` 限制用户上传的图片格式和大小。 +`beforeUpload` 的返回值可以是一个 Promise 以支持也支持异步检查 + + + +#### 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. + + +```html + + + +``` + + diff --git a/components/upload/demo/basic.md b/components/upload/demo/basic.md new file mode 100644 index 000000000..29c2873d7 --- /dev/null +++ b/components/upload/demo/basic.md @@ -0,0 +1,43 @@ + +#### 点击上传 +经典款式,用户点击按钮弹出文件选择框。 + + + +#### Upload by clicking +Classic mode. File selection dialog pops up when upload button is clicked. + + +```html + + +``` + diff --git a/components/upload/demo/defaultFileList.md b/components/upload/demo/defaultFileList.md new file mode 100644 index 000000000..268f905ee --- /dev/null +++ b/components/upload/demo/defaultFileList.md @@ -0,0 +1,54 @@ + +#### 已上传的文件列表 +使用 `defaultFileList` 设置已上传的内容。 + + + +#### Default Files +Use `defaultFileList` for uploaded files when page init. + + +```html + + +``` + + diff --git a/components/upload/demo/drag.md b/components/upload/demo/drag.md new file mode 100644 index 000000000..b45e01c34 --- /dev/null +++ b/components/upload/demo/drag.md @@ -0,0 +1,44 @@ + +#### 拖拽上传 +把文件拖入指定区域,完成上传,同样支持点击上传。 +设置 `multiple` 后,在 `IE10+` 可以一次上传多个文件。 + + + +#### Drag and Drop +Classic mode. File selection dialog pops up when upload button is clicked. + + +```html + + +``` + + diff --git a/components/upload/demo/fileList.md b/components/upload/demo/fileList.md new file mode 100644 index 000000000..c4e0b4088 --- /dev/null +++ b/components/upload/demo/fileList.md @@ -0,0 +1,69 @@ + +#### 完全控制的上传列表 +使用 `fileList` 对列表进行完全控制,可以实现各种自定义功能,以下演示三种情况: +1) 上传列表数量的限制。 +2) 读取远程路径并显示链接。 +3) 按照服务器返回信息筛选成功上传的文件。 + + + +#### 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. + + +```html + + +``` + + diff --git a/components/upload/demo/index.vue b/components/upload/demo/index.vue new file mode 100644 index 000000000..d0f43287d --- /dev/null +++ b/components/upload/demo/index.vue @@ -0,0 +1,71 @@ + diff --git a/components/upload/demo/picture-card.md b/components/upload/demo/picture-card.md new file mode 100644 index 000000000..9a4d53791 --- /dev/null +++ b/components/upload/demo/picture-card.md @@ -0,0 +1,73 @@ + +#### 照片墙 +用户可以上传图片并在列表中显示缩略图。当上传照片数到达限制后,上传按钮消失。 + + + +#### Pictures Wall +After users upload picture, the thumbnail will be shown in list. The upload button will disappear when count meets limitation. + + +```html + + + +``` + + diff --git a/components/upload/demo/picture-style.md b/components/upload/demo/picture-style.md new file mode 100644 index 000000000..4e2792387 --- /dev/null +++ b/components/upload/demo/picture-style.md @@ -0,0 +1,75 @@ + +#### 图片列表样式 +上传文件为图片,可展示本地缩略图。`IE8/9` 不支持浏览器本地缩略图展示([Ref](https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL)),可以写 `thumbUrl` 属性来代替。 + + + +#### 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. + + +```html + + + +``` + + + diff --git a/components/upload/demo/upload-manually.md b/components/upload/demo/upload-manually.md new file mode 100644 index 000000000..99dc94bb5 --- /dev/null +++ b/components/upload/demo/upload-manually.md @@ -0,0 +1,91 @@ + +#### 手动上传 +`beforeUpload` 返回 `false` 后,手动上传文件。 + + + +#### Upload manually +Upload files manually after `beforeUpload` returns `false`. + + +```html + + + +``` + + + diff --git a/components/upload/index.en-US.md b/components/upload/index.en-US.md new file mode 100644 index 000000000..d139a525a --- /dev/null +++ b/components/upload/index.en-US.md @@ -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. **Warning:this 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 identifier,negative is recommend,to prevent interference with internal generated id + name: 'xx.png' // file name + status: 'done', // options:uploading, 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. + diff --git a/components/upload/index.jsx b/components/upload/index.jsx new file mode 100644 index 000000000..0b36049bd --- /dev/null +++ b/components/upload/index.jsx @@ -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 diff --git a/components/upload/index.zh-CN.md b/components/upload/index.zh-CN.md new file mode 100644 index 000000000..cffb817a2 --- /dev/null +++ b/components/upload/index.zh-CN.md @@ -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` 上传中的服务端响应内容,包含了上传进度等信息,高级浏览器支持。 diff --git a/components/upload/interface.jsx b/components/upload/interface.jsx new file mode 100755 index 000000000..42d5916c0 --- /dev/null +++ b/components/upload/interface.jsx @@ -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, +} diff --git a/components/upload/style/index.jsx b/components/upload/style/index.jsx new file mode 100644 index 000000000..339745e3b --- /dev/null +++ b/components/upload/style/index.jsx @@ -0,0 +1,6 @@ +import '../../style/index.less' +import './index.less' + +// style dependencies +import '../../progress/style' +import '../../tooltip/style' diff --git a/components/upload/style/index.less b/components/upload/style/index.less new file mode 100644 index 000000000..00298f766 --- /dev/null +++ b/components/upload/style/index.less @@ -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; + } +} diff --git a/components/upload/utils.jsx b/components/upload/utils.jsx new file mode 100644 index 000000000..44093e471 --- /dev/null +++ b/components/upload/utils.jsx @@ -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 +} diff --git a/package.json b/package.json index 4d9f41efa..3bf6f61a8 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/site/components.js b/site/components.js index 3bf04be88..24c290ea0 100644 --- a/site/components.js +++ b/site/components.js @@ -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 diff --git a/site/demo.js b/site/demo.js index 9b1bcf475..a71a8e877 100644 --- a/site/demo.js +++ b/site/demo.js @@ -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' diff --git a/site/routes.js b/site/routes.js index 2b214efe2..f0194af1c 100644 --- a/site/routes.js +++ b/site/routes.js @@ -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}`), } }