spring&elementUI实现文件上传

spring&elementUI实现文件上传

1.elementUI上传文件组件

1.1组件

<!--el-upload:上传组件 -->
<!--action:上传的提交地址 -->
<!--auto-upload:选中文件后是否自动上传 -->
<!--name:上传文件的名称,服务端可以根据名称获得上传的文件对象 -->
<!--show-file-list:是否显示已上传文件列表 -->
<!--on-success:文件上传成功时的钩子 -->
<!--before-upload:上传文件之前的钩子-->
<el-upload
	class="avatar-uploader"
	action="/setmeal/upload.do"
	:auto-upload="true"
	name="imgFile"
	:show-file-list="false"
	:on-success="handleAvatarSuccess"
	:before-upload="beforeAvatarUpload">
<!--用于上传图片预览-->
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<!--用于展示上传图标,就是现在默认显示的+号-->
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>

1.2上传图片之前的钩子函数

//上传图片之前执行
beforeAvatarUpload(file) {
	const isJPG = file.type === 'image/jpeg';
	const isLt2M = file.size / 1024 / 1024 < 2;
	if (!isJPG) {
		this.$message.error('上传套餐图片只能是 JPG 格式!');
	}
	if (!isLt2M) {
		this.$message.error('上传套餐图片大小不能超过 2MB!');
	}
	return isJPG && isLt2M;
}

1.3上传成功之后的钩子函数

//文件上传成功后的钩子,response为服务端返回的值,file为当前上传的文件封装成的js对象
handleAvatarSuccess(response, file) {
    this.imageUrl = 'http://qeh8a93e0.bkt.clouddn.com/'+response.data;
    this.$message({
        type:response.flag?'success':'error',
        message: response.message
    });
    this.formData.img = response.data;
}

2.springmvc配置

<!--文件上传组件-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="104857600" />
    <property name="maxInMemorySize" value="4096" />
    <property name="defaultEncoding" value="UTF-8"/>
</bean>

3.controller测试代码

@RequestMapping("/upload")
public Result upload(@RequestParam("imgFile") MultipartFile imgFile){
    try {
        //获取原始文件名
        String originalFilename = imgFile.getOriginalFilename();
        //如:03a36073-a140-4942-9b9b-712cecb144901.jpg
        //获取最后一个.的索引
        int index = originalFilename.indexOf(".");
        //获取文件的后缀名,减一是为了把.也截取出来
        String suffix = originalFilename.substring(index - 1);
        //使用UUID拼接文件名,防止重复
        String fileName = UUID.randomUUID().toString()+suffix;
        //利用七牛云上传工具类上传图片
        QiniuUtils.upload2Qiniu(imgFile.getBytes(),fileName);

        return new Result(true,MessageConstant.PIC_UPLOAD_SUCCESS,fileName);
    } catch (Exception e) {
        e.printStackTrace();
        return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
    }
}

4.pom.xml

<!-- 文件上传依赖包 -->
<dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
</dependency>
<!-- 文件上传包 -->
<dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
</dependency>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值