<!-- 图片上传 -->
<el-form-item>
<el-upload
class="upload-demo"
:before-upload="beforeUpload"
:on-remove="onRemove"
:on-success="onSuccess"
:on-exceed="onExceed"
:file-list="fileList"
:limit="1"
action="http://localhost:8000/car-app/user/upload"
list-type="picture"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg文件,且不超过1MB</div>
</el-upload>
</el-form-item>
数据以及钩子函数
data() {
return {
ruleForm: {
pic:'',
},
fileList:[],
}
},
methods: {
//文件上传的钩子函数 做校验
beforeUpload(file){
let isJPG = file.type === 'image/jpeg'
let isLt1MB = file.size /1024/1024 < 1
if(!isJPG) {
this.$message.error('只能上传JPG格式图片')
return false
}
if(!isLt1MB){
this.$message.error('文件必须小于1MB')
return false
}
return true
},
//超出文件上传限制时的钩子
onExceed(file,fileList){
this.$message.error("只能上传一张图片")
},
//文件删除时执行的的钩子
onRemove(file,fileList){
this.ruleForm.pic = ''
},
//文件上传成功的钩子函数
onSuccess(response,file,fileList){
//console.log(response);
this.ruleForm.pic=response.data
}
}
后台处理上传
@Value("${upload.dir}")
private String uploadDirectory;
@Value("${upload.path}")
private String path;
@PostMapping("/upload")
public ResultVo upload(MultipartFile file) throws IOException {
String originalFilename=file.getOriginalFilename();
String suffix = FilenameUtils.getExtension(originalFilename);
String uuid = UUID.randomUUID().toString().replaceAll("-","");
String newFilename = uuid+"."+suffix;
File uplodDir = new File(this.uploadDirectory);
if(!uplodDir.exists()){
uplodDir.mkdir();
}
File newFile = new File(this.uploadDirectory,newFilename);
file.transferTo(newFile);
String picPath = path + newFilename;
log.info("图片地址-{}",picPath);
return ResultVo.success(picPath);
}
返回值格式类
ValidationUtil
import com.etoak.exception.ParamException;
import org.springframework.util.CollectionUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.Validator;
import java.util.Set;
public class ValidationUtil {
private static Validator validator;
static {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
public static void validatorObject(Object object){
Set<ConstraintViolation<Object>> violations =
validator.validate(object);
if(!CollectionUtils.isEmpty(violations)){
StringBuffer errorMsgBuf = new StringBuffer();
for(ConstraintViolation violation : violations){
// 错误的校验消息
String message = violation.getMessage();
errorMsgBuf.append(message).append("; ");
}
//抛出自定义异常向前端发送错误信息
throw new ParamException(errorMsgBuf.toString());
}
}
}