上传文件就按照element官方文档就可以实现上传:代码如下
<el-upload
:action="#"
:before-upload="beforeUpload"
:auto-upload="true"
:multiple="false" ref="newupload" accept="application/vnd.openxmlformats- officedocument.spreadsheetml.sheet" //上传的文件格式
> <el-button size="small" type="primary">上传文件</el-button> </el-upload>
============js部分===================
beforeUpload (file) {
let fd = new FormData()
fd.append('excelFile', file) // 传文件
// fd.append('srid', this.aqForm.srid) // 传其他参数
this.$http.post(url, fd).then(res => {
console.log('文件上传成功')
})
上传图片和图片的格式,大小,宽高校验
<el-upload
class="avatar-uploader"
accept="image/jpeg,image/png"
:http-request="upLoadCouponInfo" //自定义上传
:action="doUpload" // 定义为空的请求地址
:show-file-list="false"
:on-success="handleAvatarSuccessCoupon"
:before-upload="beforeAvatarUpload">
<img v-if="couponInfo.bgimageUrl" :src="couponInfo.bgimageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
<div class="tips-msg" slot="tip" style="font-size:12px;margin:-10px 0 0 70px">只能上传jpg/png,720*420且不超过400kb</div>
</el-upload>
==================js代码================
// 自定义上传图片
upLoadCouponInfo (file) {
const formData = new FormData()
formData.append('file', file.file)
Axios.post('url', formData).then(res => {
console.log(上传成功)
})
},
// 校验图片上传
beforeAvatarUpload (file) {
const isLt400k = file.size / 1024 < 400
const img = this.imgVerify(file)
if (!isLt400k) {
this.$message.error('上传头像图片大小不能超过 400KB!')
}
let Size = this.imgWidthHeight(file, 720, 420)
return img && isLt400k && Size
},
/**
* 图片校验格式封装
* params:
* file上传的图片文件
*/
imgVerify (file) {
const isJPG = file.type === 'image/jpeg'
const isPNG = file.type === 'image/png'
if (!isJPG && !isPNG) {
this.$message.error('上传头像图片只能是 JPG或者png 格式!')
}
return (isJPG || isPNG)
},
/**
* 图片高度和宽度的校验封装
* params:
* file上传的图片文件
* width、height限制的图片宽高
*/
imgWidthHeight (file, width, height) {
const isSize = new Promise(function (resolve, reject) {
let _URL = window.URL || window.webkitURL
let img = new Image()
img.onload = function () {
let valid = img.width === width && img.height === height
valid ? resolve() : reject(new Error())
}
img.src = _URL.createObjectURL(file)
}).then(() => {
return file
}, () => {
this.$message.error(`上传的图片尺寸必须是${width}*${height}!`)
return Promise.reject(new Error(false))
})
return isSize
},
有更好的方法欢迎指教!vx:jiaomi889988
原文出处:https://www.cnblogs.com/bai-xue/p/10649519.html
来源:oschina
链接:https://my.oschina.net/u/4277138/blog/3266877