一、引入阿里云依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
二、封装OSSUtil类用于获取路径,获取上传后的名字
1.封装获取路径的方法
相关代码如下
//封装的方法,用于获取路径
public static String upload(MultipartFile myfile){
// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
String endpoint = "oss-cn-hangzhou.aliyuncs.com";
// 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
String accessKeyId = "你的密匙的ID";
String accessKeySecret = "你的密匙的密码";
// 填写Bucket名称,例如examplebucket。
String bucketName = "你的Bucket的名字";
// 上传到oss后会根据日期创建文件夹,调用自己封装好的生成名字和日期的方法
String objectName=fileName(myfile);
// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
try {
InputStream inputStream = myfile.getInputStream();
// 创建PutObject请求。
ossClient.putObject(bucketName, objectName, inputStream);
} catch (Exception oe) {
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
String url="https://"+bucketName+"."+endpoint+"/"+objectName;
return url;
}
2.封装获取上传后名字的方法
相关代码如下
public static String fileName(MultipartFile myfile){
Calendar calendar=Calendar.getInstance();
String objectName=calendar.get(Calendar.YEAR)+"/"+(calendar.get(Calendar.MONTH)+1)+"/"+calendar.get(Calendar.DATE)+"/"+
UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
return objectName;
}
三、创建User实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String username;
private String password;
private String name;
//用于接收图片路径
private String avatarUrl;
}
四、创建CommResult类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CommonResult {
private Integer code;
private String msg;
private Object data;
}
五、创建前台element ui 界面
表单提交,含头像。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<!--引入element得css样式-->
<link type="text/css" rel="stylesheet" href="css/index.css"/>
<!--引入vue得js文件 这个必须在element之前引入-->
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/qs.min.js"></script>
<script type="text/javascript" src="js/axios.min.js"></script>
<!--element得js文件-->
<script type="text/javascript" src="js/index.js"></script>
</head>
<body>
<div id="app">
<el-form label-width="80px" :model="userForm">
<%--上传头像部分--%>
<el-form-item label="头像:">
<el-upload
class="avatar-uploader"
action="uploadAvatar"
: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>
</el-form-item>
<%--表单数据部分--%>
<el-form-item label="账号:">
<el-input v-model="userForm.username"></el-input>
</el-form-item>
<el-form-item label="密码:">
<el-input v-model="userForm.password"></el-input>
</el-form-item>
<el-form-item label="姓名:">
<el-input v-model="userForm.name"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">上传信息</el-button>
</el-form-item>
</el-form>
</div>
</body>
<script>
var app=new Vue({
el:"#app",
data:{
userForm:{},
imageUrl:""
},
methods:{
handleAvatarSuccess(result,file){
this.imageUrl=result.data;
console.log(this.imageUrl);
//为表单对象添加头像地址的属性
this.userForm.avatarUrl=this.imageUrl;
},
//提交
onSubmit(){
axios.post("addUser",this.userForm).then(function(result){
console.log(result.data)
app.$message.success(result.data.msg)
});
},
//上传前触发的方法
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg';
const isPNG = file.type === 'image/png';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG 格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isJPG && isLt2M;
}
}
})
</script>
<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>
</html>
六、后台controller层代码
@RestController//相当于 @Controller注解+@ResponseBody注解
public class UserController {
@RequestMapping(value = "uploadAvatar")
public CommonResult uploadAvatar(MultipartFile file){
//1.调用自己封装在工具类的方法
String avater= OSSUtil.upload(file);
//2.返回数据
return new CommonResult(2000,"上传成功",avater);
}
@RequestMapping(value = "addUser")
public CommonResult addUser (@RequestBody User user){
System.out.println(user);
return new CommonResult(2000,"提交成功",null);
}
}