注: 本文中所有的原始文件对象统称为原始文件,而经过包装后的文件对象称为文件对象,这个文件对象的结构如下:
基本用法
export default {
methods: {
filesAdded(files) {
let hasIgnore = false
const maxSize = 1 * 1024 * 1024 // 1M
for (let k in files) {
const file = files[k]
if (file.size > maxSize) {
file.ignore = true
hasIgnore = true
}
}
hasIgnore && this.- createToast({
type: 'warn',
time: 1000,
}).show()
}
}
}
配置 action 表示上传的 URL 地址,而 simultaneous-uploads 则表示支持的并发上传个数。
通过 files-added 事件可以实现文件过滤,设置 file.ignore = true 即可。
压缩图片且通过 Base64 上传
import compress from '../../modules/image'
export default {
data() {
return {
target: '//jsonplaceholder.typicode.com/photos/',
prop: 'base64Value'
}
}
},
methods: {
processFile(file, next) {
compress(file, {
compress: {
width: 1600,
height: 1600,
quality: 0.5
}
}, next)
},
file.base64Value = file.file.base64
}
}
}
process-file 则是一个函数,主要用于处理原生文件的,调用 next 回调的话,参数是处理完的文件对象,这里示例的就是调用 compress 做压缩,处理完后会回调 next。
file-submitted 事件则是每个文件处理完后添加到 upload 实例的 files 数组中后触发,参数就是一个处理后的文件对象。
自定义结构样式
使用默认插槽来实现自定义结构,在此基础上自定义样式。
export default {
data() {
return {
action: '//jsonplaceholder.typicode.com/photos/',
}
},
methods: {
addedHandler() {
const file = this.files[0]
file && this.- refs.upload.removeFile(file)
},
errHandler(file) {
// const msg = file.response.message
this.- createToast({
type: 'warn',
txt: 'Upload fail',
time: 1000
}).show()
}
}
上述示例实现的效果就是点击上传(一次只能选择一张)一张图片,此图片就会直接展示,而上传按钮本身则是不可见,覆盖在图片预览区域上。再次重新选择图片,就会移除掉上次选择的图片,重新展示新选择的图片。
action 子配置项
如果 action
是字符串,则会被处理成 { target: action }
这样结构。
processFile 子配置项
一个函数,这个函数有两个参数:(file, next)
,file
就是原始文件,next
为处理完毕后的回调函数,调用的时候需要传入处理后的文件。