####注:代码可以换接口可以直接使用
一:需求说明
上传图片,首先要上传到后端给的一个接口中,从这个接口获取返回的file相关的信息,拿到信息进行处理,最后拿到相关参数,作为接口入参,传到我们最后上传图片的接口
二:步骤说明
- 使用elementUI中的el-upload组件
- 介绍属性功能
-
action:表示图片要上传到的后台API地址, -
on-change:文件状态改变时,也就是文件上传成功或者失败时会可以触发这个方法,获取返回结果 -
before-upload:上传图片之后,可以获取到图片/文件的相关数据 -
multiple:是否支持多选文件,根据需求设置true/false -
show-file-list:是否显示已上传文件列表,根据需求设置true/false -
drag: 是否启用拖拽上传,默认false -
accept:接受上传的[文件类型](thumbnail-mode 模式下此参数无效)
- 代码展示
4. 代码复制
<el-form-item style="display:flex;" label="上传图片:">
<el-upload
action="{ms:global.host/}/envTransManager/minio?"
:show-file-list="false"
:multiple="false"
:on-change="uploadFile"
:before-upload="beforeUpload"
drag
accept="image/jpg,image/jpeg,image/png">
<i v-if="imageUrl" class="el-icon-circle-close deleteImg" @click.stop="handleRemove"></i>
<img v-if="imageUrl" :src="imageUrl" class="el-upload--picture-car" />
<div v-else>
<i class="el-icon-picture" style="margin-top: 40px; font-size: 40px; color: #999a9c" />
<div>上传图片</div>
<div>格式为 png、jpeg 或 jpg</div>
</div>
</el-upload>
</el-form-item>
<script>
export default {
data(){
return {
filesData:{},
imageUrl:"",
}
},
methods:{
//上传图片
uploadFile(item) {
this.filesData = item.raw; // 图片文件
this.imageUrl = URL.createObjectURL(item.raw); // 图片上传浏览器回显地址
},
beforeUpload(file) {
const formData = new FormData();
let fileNameOne = file.name.lastIndexOf('.') //取到文件名开始到最后一个点的长度
let fileNameLength = file.name.length //取到文件名长度
let fileFormat = file.name.substring(fileNameOne + 1, fileNameLength) //截去后缀名
let suffixY = ''
if (fileFormat == 'png') {
suffixY = 'image/png'
} else if (fileFormat == 'jpg') {
suffixY = 'image/jpeg'
} else if (fileFormat == 'gif') {
suffixY = 'image/gif'
} else if (fileFormat == 'doc' || fileFormat == 'docx') {
suffixY = 'application/msword'
} else if (fileFormat == 'pdf') {
suffixY = 'application/pdf'
} else if (fileFormat == 'json') {
suffixY = 'application/json'
}
//修改文件名为时间戳
let fileNamecutOut = file.name.substring(0, fileNameOne) // 对文件名进行切割(回去文件名)
//新的文件名称
let fileNameTime = this.getUUID() + Date.now() + '.' + fileFormat
let File = window.File
new File([], '')
let renameFile = new File([file], fileNameTime, { type: file.type })
var url = '{ms:global.host/}/envTransManager/minio?bucketName=flow&objectName=/deposit/paymentVoucher/' + fileNameTime
axios.get(url, {
headers: {
'auth-token': 'Bearer ' + this.token
},
}).then(res => {
this.formData.variables.applyDeposit.paymentVoucher = res.data.data.downloadPath
axios.put(res.data.data.uploadPath,
renameFile, {
headers: {
'Content-Type': suffixY,
upload: 'upload',
'x-amz-acl': 'public-read'
},
}).then(res => {
}).catch(err => { })
})
},
getUUID() { // 这个方法别动 直接用
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (Math.random() * 16) | 0,
v = c == 'x' ? r : (r & 0x3) | 0x8
return v.toString(16)
})
}
}
}
</script>
如果想看封装好的上传文件的upload.js如何配合el-upolad使用,推荐这篇文章 juejin.cn/spost/74292…