文件上传
1. vue+element 文件上传
<el-upload
class="upload-demo"
//必选参数,上传的地址
action="https://jsonplaceholder.typicode.com/posts/"
//是否支持多选文件
multiple
//最大允许上传个数
:limit="3"
//覆盖默认的上传行为,可以自定义上传的实现
:http-request="uploadFn"
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
//上传函数
uploadFn( files //element默认传参-选择的文件){
//获取文件信息
let file = files.file
// 将文件放入formData中
let formData = new FormData()
//不一定添加属性名叫 'file' , 可以自定义
formData.append('file', file)
//接口函数
axiosFn(formData).then( res=>{
//提示结果
this.$message.success( res.msg )
} )
}
//上传前钩子,判断文件类型、大小等
:before-upload = "beforeUpload"
beforeUpload( file//默认传参 ){
//判断类型
const typeName = file.type === 'image/jpeg' || file.type === 'image/png'
if (!typeName) {
this.$message.error('You can only upload JPG file!')
}
//判断大小
const isLt200KB = file.size / 1024 < 200
if (!isLt200KB) {
this.$message.error('Image must smaller than 200KB!')
}
//若返回 false,则停止上传 , 提示删掉该文件(自动调用删除方法)