概述
ImgUpload.vue
<template>
<el-upload
class="img-upload"
ref="upload"
action="http://localhost:9527/img/upload"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove"
:on-success="handleSuccess"
multiple
:limit="1"
:on-exceed="handleExceed"
:file-list="fileList">
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</template>
<script>
export default {
name: 'ImgUpload',
data () {
return {
fileList: [],
url: ''
}
},
mounted(){
this.fileList = []
},
methods: {
handleRemove (file, fileList) {
},
handlePreview (file) {
},
handleExceed (files, fileList) {
this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)
},
beforeRemove (file, fileList) {
return this.$confirm(`确定移除 ${file.name}?`)
},
handleSuccess (response) {
this.url = response.result
this.$emit('onUpload')
this.$message.warning('上传成功')
},
clear () {
this.$refs.upload.clearFiles()
}
}
}
</script>
使用
import ImgUpload from '@/components/utils/ImgUpload
components:{ImgUpload}
- 代码中使用
<el-input v-model="img" :disabled="true"></el-input> <ImgUpload @onUpload="uploadImg" ref="imgUpload"></ImgUpload>
- uploadImg
uploadImg() { this.img = this.$refs.imgUpload.url; },
后台处理返回图片名
@RestController
@RequestMapping("/img")
public class ImgController {
@Value("${upload.image.path}")
private String imagePath;
@PostMapping("/upload")
public Response uploadImg(HttpServletRequest req, MultipartFile file){
if (file.isEmpty()) {
System.out.println("文件为空");
return Response.Fail("文件为空");
}
String fileName = file.getOriginalFilename(); // 文件名
String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 后缀名
fileName = UUID.randomUUID() + suffixName; // 新文件名
File dest = new File(imagePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
return Response.Fail("上传失败");
}
return Response.Success("上传成功!",fileName);
}
最后
以上就是认真老虎为你收集整理的[Vue]对图片上传组件的封装的全部内容,希望文章能够帮你解决[Vue]对图片上传组件的封装所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复