ElementUI图片上传组件

本文介绍了使用Element UI实现前端图片上传功能,包括限制上传格式为JPG且大小不超过1MB的校验,以及上传成功后的处理。同时,后台通过Spring Boot接收文件,保存到指定目录,并返回图片路径。此外,还提供了文件超出限制和删除的处理策略。
摘要由CSDN通过智能技术生成
<!-- 图片上传 -->
    <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());
        }
    }
}
Element UI 提供了一个 `el-upload` 组件,可以用于上传图片。 以下是一个简单的示例: ```html <template> <el-upload class="avatar-uploader" action="/upload" :show-file-list="false" :on-success="handleSuccess" :before-upload="beforeUpload"> <img v-if="imageUrl" :src="imageUrl" class="avatar"> <i v-else class="el-icon-plus avatar-uploader-icon"></i> </el-upload> </template> <script> export default { data() { return { imageUrl: '', }; }, methods: { handleSuccess(response, file) { this.imageUrl = URL.createObjectURL(file.raw); }, beforeUpload(file) { const isJPG = file.type === 'image/jpeg'; const isPNG = file.type === 'image/png'; const isLt2M = file.size / 1024 / 1024 < 2; if (!isJPG && !isPNG) { this.$message.error('上传头像图片只能是 JPG/PNG 格式!'); return false; } if (!isLt2M) { this.$message.error('上传头像图片大小不能超过 2MB!'); return false; } return true; }, }, }; </script> ``` 这个示例中,我们使用 `el-upload` 组件来上传图片。它有几个关键属性: - `action`:上传图片的地址。 - `show-file-list`:是否显示已上传的文件列表。 - `on-success`:上传成功的回调函数。 - `before-upload`:上传前的回调函数。 在这个示例中,我们使用 `handleSuccess` 函数来处理上传成功后的结果。在该函数中,我们使用 `URL.createObjectURL()` 来生成一个临时的 URL,用于显示上传的图片。 在 `beforeUpload` 函数中,我们可以进行一些上传前的检查,例如文件类型、大小等。如果检查不通过,可以通过返回 `false` 来阻止上传。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值