vue+element upload手动上传文件,自定义文件名字
上传后改变图片的名字,进行自定义,避免传重复的图片<el-uploadclass="upload-demo":action="uploadUrl":file-list="ruleForm.fileList":before-upload="beforeUploadFile":on-error="handleError":on-exceed="h..
·
上传后改变图片的名字,进行自定义,避免传重复的图片
<el-upload
class="upload-demo"
:action="uploadUrl"
:file-list="ruleForm.fileList"
:before-upload="beforeUploadFile"
:on-error="handleError"
:on-exceed="handleExceed"
:limit="1"
:on-progress="upLoading"
>
<el-button
v-loading.fullscreen.lock="fullscreenLoading"
size="small"
type="primary"
>
点击上传
</el-button>
<div slot="tip" class="el-upload__tip">
只能上传jpg/png文件,且不超过500kb
</div>
</el-upload>
里面的action,不能为空,官方为必填,否则会报错,随便写个,只要不为空就行
uploadUrl() {
let downLoadUrl = location.href.indexOf('education') > -1 ? '' : '/api'
return downLoadUrl + '/api-system/sys/file/uploadFile'
}
相关的验证方法
upLoading() {
console.log('正在上传')
this.fullscreenLoading = true
},
resetForm(formName) {
this.$router.history.go(-1)
this.$refs[formName].resetFields()
},
handleChange(file, fileList) {
/* this.fileList = fileList.slice(-3) */
},
// 文件上传成功时的钩子
handleSuccess(res, file, fileList) {
console.log(file, '上传成功', fileList)
this.fullscreenLoading = false
this.ruleForm.fileList = [
{ name: file.response.datas.name, url: file.response.datas.path }
]
this.$message.success('文件上传成功')
},
// 文件上传失败时的钩子
handleError(err, file, fileList) {
this.$message.error('文件上传失败')
this.fullscreenLoading = false
return false
},
beforeUploadFile(file) {
/* debugger */
let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
let size = file.size / 1024 / 1024
/* console.log(extension, 'extension') */
if (extension !== 'jpg' && extension !== 'png') {
this.$message.warning('只能上传后缀是jpg/png的文件')
return false
} else if (size > 10) {
this.$message.warning('文件大小不得超过10M')
return false
} else {
}
const timeStamp = new Date() - 0
let nums = this.randomString(5)
const copyFile = new File(
[file],
`${timeStamp}_${nums}.${file.name.split('.')[1]}`
)
this.uploadFile(copyFile)
return false
},
uploadFile(file) {
//const formdata = new FormData()
//这里后台需要的就是file文件,不是formdata,所以我们不用生成formdata,看各自的需求吧
//formdata.append('file', file)
this.postForm(file)
},
postForm(file) {
//uploadPic为后台接口方法
uploadPic({ file })
.then(res => {
if (res.resp_code == 0) {
// do something
this.fullscreenLoading = false
//上传成功后回显的数据
this.ruleForm.fileList = [
{ name: res.datas.name, url: res.datas.path }
]
this.$message.success('文件上传成功')
} else {
this.$message.error(res.msg || res.message || '文件上传失败')
}
})
.catch(err => {
this.$message.error(err.message || '文件上传失败')
})
},
handleExceed(files, fileList) {
this.fullscreenLoading = false
this.$message.warning(
`当前限制选择 1 个文件,本次选择了 ${
files.length
} 个文件,共选择了 ${files.length + fileList.length} 个文件`
)
},
//名字随机数生成方法
randomString(e) {
e = e || 32
var t = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678',
a = t.length,
n = ''
for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a))
return n
}
更多推荐
已为社区贡献3条内容
所有评论(0)