后端需要 BASEE64 格式
// console.log(e.target.files[0])
// img 标签的 src 属性 只能设置两种值:
// URL 和 BASE64 (Data URL)
const files = e.target.files
// 判断files 的长度是否大于零
if (files.length > 0) {
// files[0] 是一个对象
// 目标:将这个对象 转成BASE64 格式 的字符串
// FileReader 文件读取器
// 1. 创建FileReader 对象
const fr = new FileReader()
// 2. 读取文件转成 BASE64
fr.readAsDataURL(files[0])
// 3. 监听 事件 ,得到结果
fr.onload = (e) => {
// console.log(e)
// avater 是定义的请求体
this.avatar = e.target.result
}
} else {
this.avatar = ''
}
},
后端需要 blob二进制格式 就是URL
const files = e.target.files
// console.log(e)
if (files.length > 0) {
this.ruleForm.cover_img = files[0]
// File 对象 转为 BASE64 字符串,设置给img 标签的src
// 转为BASE64 好处与坏处
// 好处 : 减少发送请求的次数
// 坏处 : 会额外 占用 33% 左右的体积大小
// 结论 : 小图片推荐转为 BASE64 大图片不推荐
// 转为 BASE64
// const fr = new FileReader()
// fr.readAsDataURL(files[0])
// fr.onload = e => {
// // console.log(e)
// this.preview = e.target.result
// }
// img标签的 src 只能设置为两种 : 1.BASE64 2.URL
// 怎么将File 对象转成 URL?
// URL.createObjectURL
// 作用: 将 Blob 或 File 对象转为 URL
// 参数 : Blob 或 File 对象
// 返回值 URL
// 这个 URL 的生命周期 和 当前窗口一致,窗口关闭后就不能访问该 URL 了
this.preview = URL.createObjectURL(files[0])
// 移出校验结果
this.$refs.ruleForm.clearValidate('cover_img')
} else {
this.ruleForm.cover_img = ''
}
},
由于此接口涉及到文件上传的功能,因此提交的请求体,必须是 FormData 格式! 请求体 FormData 格式 传入
// fd.append('title', this.ruleForm.title)
// fd.append('cate_id', this.ruleForm.cate_id)
// fd.append('content', this.ruleForm.content)
// fd.append('cover_img', this.ruleForm.cover_img)
// fd.append('state', this.ruleForm.state)
// for in 方法
// for (const k in this.ruleForm) {
// fd.append(k, this.ruleForm[k])
// };
// keys 可以获取对象的所有属性名,返回值是一个数组
Object.keys(this.ruleForm).forEach(k => fd.append(k, this.ruleForm[k]))
const { data: res } = await this.$http.post('/my/article/add', fd)