前端页面(elementui)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- import CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
</head>
<body>
<div id="app">
<el-upload
class="avatar-uploader"
action="http://localhost:8080/setMeal/upload"
:auto-upload="autoUpload"
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>
</div>
</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
new Vue({
el: '#app',
data() {
return {
imageUrl: ''
};
},
methods: {
handleAvatarSuccess(res, file) {
this.imageUrl = URL.createObjectURL(file.raw);
},
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;
}
}
})
</script>
</html>
后端
maven坐标:
<!-- 上传工具 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!--七牛云-->
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>7.2.0</version>
</dependency>
在spring-mvc.xml配置文件中配置上传解析器
<!-- 配置文件上传解析器-->
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">
<property value="104857600" name="maxUploadSize"/>
<property value="4096" name="maxInMemorySize"/>
<property value="UTF-8" name="defaultEncoding"/>
</bean>
controllerweb层:
@RequestMapping("upload")
public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
try {
String filename = imgFile.getOriginalFilename();
String savFileName = UUID.randomUUID().toString().replace("-", "") + "_" + filename;
QiniuUtils.upload2Qiniu(imgFile.getBytes(), savFileName);
jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES, savFileName);
return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, QiniuUtils.qiniu_img_url_pre + savFileName);
} catch (Exception e) {
e.printStackTrace();
return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
}
}
七牛工具类:
public class QiniuUtils {
public static String qiniu_img_url_pre = "http://qdn8v47w0.bkt.clouddn.com/";
public static String accessKey = "M8AHxRBhBw7Hkmsc1NfdTZpT4ZZA5WE1t000OI51";
public static String secretKey = "-ahel4qCJgVaQvf6LggHtBK5xlYtIY7JNast21Ck";
public static String bucket = "health-test-0";
public static void upload2Qiniu(byte[] bytes, String uploadFileName) {
Configuration cfg = new Configuration(Zone.zone2());
UploadManager uploadManager = new UploadManager(cfg);
String key = uploadFileName;
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(bytes, key, upToken);
System.out.println(response.bodyString());
System.out.println("http://qdn8v47w0.bkt.clouddn.com/" + uploadFileName);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
ex.printStackTrace();
}
}
}
public static void deleteFileFromQiniu(String fileName) {
Configuration cfg = new Configuration(Zone.zone2());
String key = fileName;
Auth auth = Auth.create(accessKey, secretKey);
BucketManager bucketManager = new BucketManager(auth, cfg);
try {
bucketManager.delete(bucket, key);
} catch (QiniuException ex) {
System.err.println(ex.code());
System.err.println(ex.response.toString());
}
}
public static void main(String args[]) throws IOException {
String localFilePath = "C:\\Users\\Administrator\\Desktop\\test.jpg";
FileInputStream fileInputStream = new FileInputStream(localFilePath);
byte[] data = new byte[1024 * 1024];
fileInputStream.read(data);
String saveFileName = UUID.randomUUID().toString().replace("-", "");
QiniuUtils.upload2Qiniu(data, saveFileName);
deleteFileFromQiniu("19573c9b8ace4f939c658e7249215f9b_test.jpg");
}
}