目录
vue3图片上传
实现本地预览 将图片转为file对象
show-file-list:是否显示已上传文件列表
:auto-upload:是否在选取文件后立即进行上传到后台
:on-change:文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用 回调参数file,fileList
<el-upload
class="avatar-uploader"
:show-file-list="false"
:auto-upload="false"
:on-change="onSelectFile"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
</el-upload>
样式
<style scoped>
.avatar-uploader .avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
border: 1px dashed var(--el-border-color);
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
text-align: center;
}
</style>
const onSelectFile = (file) => {
//实现本地预览
imageUrl.value = URL.createObjectURL(file.raw)
// file对象赋值
formModel.value.cover_img = file.raw //赋值对象
}
实现本地预览,将图片转为base64
<el-upload
ref="imagedom"
class="avatar-uploader"
:show-file-list="false"
:auto-upload="false"
:on-change="onSelectFile"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<el-icon v-else class="avatar-uploader-icon">
<Plus />
</el-icon>
</el-upload>
<el-button type="primary" @click="Selectimg">选择头像</el-button>
<el-button @click="submit">上传头像</el-button>
获取dom元素,模拟点击
//模拟点击
const imagedom = ref('')
const Selectimg = () => {
//模拟点击上传框
imagedom.value.$el.querySelector('input').click()
}
选择图片触发事件,将图片转为base64位
const imageUrl = ref(userstore.userinfo.user_pic)
const onSelectFile = (file) => {
// 实现本地预览 转为file格式的
// imageUrl.value = URL.createObjectURL(file.raw)
// 基于FileReader 读取图片做预览 转为base64格式
const reader = new FileReader()
reader.readAsDataURL(file.raw)
reader.onload = () => {
imageUrl.value = reader.result
console.log(imageUrl.value)
}
}
基本axios,将网络图片变成file对象
// 引入axios
import axios from 'axios'
// 将网络图片转化为file对象
//参数imageUrl:网络图片地址
//参数fileName:/uploads/885eb38f6270eb10b42aedadd84fea23.jpg 为后端传来的地址
async function imageUrlToFile(imageUrl, fileName) {
try {
const response = await axios.get(imageUrl, { responseType: 'arraybuffer' })
const blob = new Blob([response.data], {
type: response.headers['content-type']
})
const file = new File([blob], fileName, {
type: response.headers['content-type']
})
return file
} catch (error) {
console.error('Error fetching the image:', error)
return null
}
}
// 调用函数将网络图片处理返回文件对象
const getfile=asnyc ()=>{
const file = await imageUrlToFile(imageUrl.value,formModel.value.cover_img)
}
上传图片接口
接口:/my/article/add
请求方式:post
body参数:form-data
注意:接口上传图片需要file对象,data需为FormData格式

1.封装接口
// 发布文章接口
export const addarticlesListServe = (data) => {
return requset.post('/my/article/add', data)
}
2.收集数据上传图片到接口
<el-button @click="addarticle"></el-button>
import { addarticlesListServe } from '@/api/article'
//设置接口数据体
const formModel = ref({
title: '',
cate_id: '',
content: '',
cover_img: '',//注意为file对象
state: '已发布'
})
//发布事件
const addarticle = async () => {
//创建formdata
const fd = new FormData()
//存入数据
for (let key in formModel.value) {
fd.append(key, formModel.value[key])
}
//发请求
const res = await addarticlesListServe(fd)
console.log(res)
}
给文件上传添加加载与默认图片
// 上传PSD文件
const onSelectPSDFile = async (file: any) => {
const fd = new FormData()
fd.append('file', file.raw)
//利用try finally 添加上传loading
try {
loading2.value = true
const res = await uploadimage(fd)
console.log('PSD文件的URL', res.path)
fromModel2.value.psdContent = res.path
} finally {
loading2.value = false // 结束加载
}
}
<el-upload
class="avatar-uploader"
:show-file-list="false"
:auto-upload="false"
v-loading="loading2"
:on-change="onSelectPSDFile"
>
<img
v-if="fromModel2.psdContent"
src="@/assets/images/PSD.png"
class="avatar"
/>
<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
</el-upload>
给图片添加表单校验
const rules = {
copyrightCertificate: [{ required: true, message: '请上传图片', trigger: 'change' }],
}
<el-form-item label="授权证书" prop="copyrightCertificate">
<el-upload
class="avatar-uploader"
:show-file-list="false"
:auto-upload="false"
v-loading="loading1"
:on-change="onSelectSQFile"
>
<img
v-if="fromModel2.copyrightCertificate"
:src="fromModel2.copyrightCertificate"
class="avatar"
/>
<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
</el-upload>
</el-form-item>
上传完成清除校验:
form2.value.clearValidate(['校验名'])
// 上传授权证书
const onSelectSQFile = async (file: any) => {
fromModel2.value.copyrightCertificate = URL.createObjectURL(file.raw) //实现本地预览
const fd = new FormData()
fd.append('file', file.raw)
try {
loading1.value = true
const res = await uploadimage(fd)
console.log('授权证书URL', res.path)
fromModel2.value.copyrightCertificate = res.path
} finally {
loading1.value = false // 结束加载
//上传完清除校验
form2.value.clearValidate(['copyrightCertificate'])
}
}
本文介绍了如何在Vue3应用中实现图片上传功能,包括本地预览转File对象、使用axios将网络图片转为File对象,以及如何将File对象通过FormData发送到后端接口。
993

被折叠的 条评论
为什么被折叠?



