使用element-ui上传文件
formData格式
组件
<el-upload
style="width: 300px"
class="upload-demo"
drag
multiple
:on-success="upSuccess"
:on-change="handleChange"
:file-list="fileList"
:http-request="httpRequest"
>
<i class="el-icon-upload" />
<div class="el-upload__text">
将文件拖到此处,或<em>点击上传</em>
</div>
<div slot="tip" class="el-upload__tip">
只能上传jpg/png文件,且不超过500kb
</div>
</el-upload>
方法
methods:{
// 上传前判断文件格式及大小
handleBeforeUpload(file, fileList) {
let res = true
// 判断文件格式
const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png')
const isPDF = file.type === 'application/pdf'
if (!isJPG && !isPDF) {
this.$message.error('上传文件只能是 图片 或 PDF 格式!')
res = false
}
// 判断文件大小
const isLt5M = file.size / 1024 / 1024 < 5
if (!isLt5M) {
this.$message.error('上传文件大小不能超过 5MB!')
res = false
}
// 判断文件是否已经上传过
for (const i in fileList) {
if (fileList[i].name === file.name) {
this.$message.error('该文件已上传过,请选择其他文件')
res = false
}
}
return res
},
// 文件列表移除文件时的钩子
handleRemove(file, fileList) {
for (const i in fileList) {
if (fileList[i].name === file.name) {
fileList.splice(i, 1)
return
}
}
},
handleExceed(files, fileList) {
this.$message.warning('最多上传一个文件,请先删除再重新上传')
}
},
// 文件上传
uploadManSystemScanFile(file) {
console.log(file) // 上传的文件
Uploadimg(file).then(res => {
if (res.code === 200) {
this.$message.success('文件上传成功')
}
})
},
}
请求函数(api)
// 图片上传
export function Uploadimg(fileobj) {
const param = new FormData()
param.append('file', fileobj.file)
return request({
url: 'file/uploadFile',
method: 'post',
headers: { 'Content-Type': 'multipart/form-data' },
data: param
})
}