vue(nuxt)+el-upload+Springboot实现表单和图片上传
我的环境是nuxt+el-upload+Springboot;<template><div><el-uploadclass="upload-demo"action="http://xball.henengsoft.com:8092/hn/uploads":limit="1"...
·
我的环境是nuxt+el-upload+Springboot;
<template>
<div>
<el-upload
class="upload-demo"
action="http://xball.henengsoft.com:8092/hn/uploads"
:limit="1"
accept="image/*"
:on-exceed = "onExceed"
:on-change="handleChange"
:on-success="uploadSuccess"
:before-upload="beforeUnload"
:beforeUpload="beforeAVatarUpload"
:auto-upload="false"
ref="upload"
:file-list="fileList">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
<button @click="sc">上传</button>
<img :src="path" style="width: 400px"/>
<!-- <el-upload drag multiple
name="multipartfiles" //后台接收文件流的参数名
ref="upload"
:limit="limit" //限制文件数量
:action="imageAction" //上传图片的访问的服务器路径
:data="uploadData" //需要携带的其他参数
:on-preview="handlePreview" //点击时触发的事件
:on-remove="handleRemove" //点击移除文件时触发的事件
:file-list="fileList" //已上传的文件list
:beforeUpload="beforeAVatarUpload" //上传之前触发的事件,我在这里做了上传文件的类型控制
:on-exceed = "onExceed" //和limit一起用 当文件数量超出限制时触发
:onError="uploadError" //上传失败时触发
:onSuccess="uploadSuccess" //上传成功时触发
:auto-upload="true"> //是否自动上传
<i class="el-icon-upload"></i>
<div class="el-upload__text">将图片拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传'jpg/png/jpeg/gif'</div>
</el-upload>-->
</div>
</template>
<script>
export default {
name:'cs',
data() {
return {
fileList: [],
path:'',
};
},
methods: {
handleChange(file, fileList) {
this.fileList = fileList.slice(-3);
console.log(fileList)
},
handleAvatarSuccess(){
this.$message({type: 'success', message: '上传成功', showClose: true});
},
uploadSuccess(e){
this.path="http://xball.henengsoft.com:8092/hn/file/download?filename="+e.path;
console.log(e.path)
},
beforeUnload(){
//自动上传触发
if(this.fileList.length>1){
this.fileList.splice(1,1);
this.$message({type: 'info', message: '请删除资源后重新上传', showClose: true});
return false;
}
return true;
},
sc(){
//手动提交
//和表单一起提交,先提交图片,后提交表单
this.$refs.upload.submit()
},
onExceed(){
//手动上传限制
this.$message({type: 'info', message: '请删除资源后重新选择', showClose: true});
},
beforeAVatarUpload(file) {
let _this = this
//resolve:同意
//reject:拒绝
return new Promise((resolve, reject) => {
debugger
let isLt2M = file.size / 1024 / 1024 > 0.1 // 判定图片大小是否小于100k
if(!isLt2M) {
resolve()
}
let image = new Image(), resultBlob = '';
image.src = URL.createObjectURL(file);
image.onload = () => {
// 调用方法获取blob格式,方法写在下边
resultBlob = _this.compressUpload(image);
resolve(resultBlob)
}
image.onerror = () => {
reject()
}
})
},
/* 图片压缩方法-canvas压缩 */
compressUpload(image) {
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
let initSize = image.src.length
let { width } = image, { height } = image
canvas. width = width
canvas.height = height
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(image, 0, 0, width, height)
// 进行最小压缩0.1
let compressData = canvas.toDataURL('image/jpeg', 0.1)
// 压缩后调用方法进行base64转Blob,方法写在下边
let blobImg = this.dataURItoBlob(compressData)
return blobImg
},
/* base64转Blob对象 */
dataURItoBlob(data) {
let byteString;
if(data.split(',')[0].indexOf('base64') >= 0) {
byteString = atob(data.split(',')[1])
}else {
byteString = unescape(data.split(',')[1])
}
let mimeString = data
.split(',')[0]
.split(':')[1]
.split(';')[0];
let ia = new Uint8Array(byteString.length)
for( let i = 0; i < byteString.length; i += 1) {
ia[i] = byteString.charCodeAt(i)
}
return new Blob([ia], {type: mimeString})
}
}
}
</script>
<style scoped>
</style>
我这里分两步提交,先上传图片在上传图片成功的回调函数uploadSuccess()提交表单;
@RequestMapping(value = "/uploads", method = RequestMethod.POST)
public R file(@RequestParam("file") MultipartFile file) {
String filePath="";
if (!file.isEmpty()) {
try {
int begin = file.getOriginalFilename().indexOf(".");
int last = file.getOriginalFilename().length();
//获得文件后缀名
String a = file.getOriginalFilename().substring(begin, last);
String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
uuid += a;
String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String paths= path + date + "\\";
// 判断文件是否为空
File file1 = new File(paths);
if (!file1.exists()) {
file1.mkdirs();//创建
}
// 文件保存路径
filePath = paths
+ uuid;
// 转存文件
file.transferTo(new File(filePath));
} catch (Exception e) {
e.printStackTrace();
}
}else
return R.error("文件不存在");
try {
filePath = java.net.URLEncoder.encode(filePath, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return R.ok().put("path", filePath);
}
后台就是存储图片并返回图片路径,第二次提交表单时一起提交。
更多推荐
已为社区贡献1条内容
所有评论(0)