spring&elementUI实现文件上传
1.elementUI上传文件组件
1.1组件
<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上传成功之后的钩子函数
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();
int index = originalFilename.indexOf(".");
String suffix = originalFilename.substring(index - 1);
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>