一.阿里云
注册登陆就不讲了,登陆进去后如下操作
1.
进入对象存储OSS 创建一个新的Bucket
随后点击新建的bucket
2.去访问RAM
前往RAM控制台
3.去创建用户
4.创建密匙
5.随后返回RAM控制台
给用户增加权限,文件上传所需权限,需要带含有OSS的权限。
6.随后进入用户将自己创建的密匙赋予给该用户,目的就是为了更安全
好的,到此为止,阿里云的配置就完成了,windows系统的操作就到此为止了,接下来是ideal的操作
二.后台配置
2.1导入依赖
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
2.2所需工具类
ResponseResult
package com.dmdd.javasecuritypractice.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 响应数据封装对象
*/
@Data
public class ResponseResult<T> {
/**
* 状态信息
*/
private ResponseStatus status;
/**
* 数据
*/
private T data;
public ResponseResult(ResponseStatus status, T data) {
this.status = status;
this.data = data;
}
/**
* 返回成功对象
* @param data
* @return
*/
public static <T> ResponseResult<T> ok(T data){
return new ResponseResult<>(ResponseStatus.OK, data);
}
/**
* 返回错误对象
* @param status
* @return
*/
public static ResponseResult<String> error(ResponseStatus status){
return new ResponseResult<>(status,status.getMessage());
}
/**
* 返回错误对象
* @param status
* @return
*/
public static ResponseResult<String> error(ResponseStatus status,String msg){
return new ResponseResult<>(status,msg);
}
/**
* 向流中输出结果
* @param resp
* @param result
* @throws IOException
*/
public static void write(HttpServletResponse resp, ResponseResult result) throws IOException {
//设置返回数据的格式
resp.setContentType("application/json;charset=UTF-8");
//jackson是JSON解析包,ObjectMapper用于解析 writeValueAsString 将Java对象转换为JSON字符串
String msg = new ObjectMapper().writeValueAsString(result);
//用流发送给前端
resp.getWriter().print(msg);
resp.getWriter().close();
}
}
OSSutils
package com.dmdd.javasecuritypractice.util;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSBuilder;
import com.aliyun.oss.OSSClientBuilder;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.URL;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
/**
* OSS文件上传工具类
*/
public class OSSUtil {
// Endpoint以杭州为例,其它Region请按实际情况填写。
private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。
private static String accessKeyId = "LTAI5tHcwsYkxjt6YxgrEVAM";
private static String accessKeySecret = "WeBHibTdv1ybo44MlEWxo7VpCXyO1l";
private static String bucketName = "dmddjly";
//目录名
public static String dir = "images";
/**
* 文件上传
* @param inputStream
* @param fileName
*/
public static void upload(InputStream inputStream, String fileName){
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
oss.putObject(bucketName,dir +"/"+ fileName,inputStream);
oss.shutdown();
}
/**
* 获得文件URL
* @param fileName
* @return
*/
public static String getURL(String fileName){
OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//设置过期时间
LocalDateTime time = LocalDateTime.now().plusDays(100);
Date expiration = Date.from(time.atZone( ZoneId.systemDefault()).toInstant());
URL url = oss.generatePresignedUrl(bucketName, dir +"/"+ fileName, expiration);
oss.shutdown();
return url.toString();
}
public static void main(String[] args) throws FileNotFoundException {
OSSUtil.upload(new FileInputStream("E:\\img\\xing.png"),"xing.png");
System.out.println(OSSUtil.getURL("xing.png"));
}
}
private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; // 云账号AccessKey有所有API访问权限,建议遵循阿里云安全最佳实践,创建并使用RAM子账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建。 private static String accessKeyId = "LTAI5tHcwsYkxjt6YxgrEVAM"; private static String accessKeySecret = "WeBHibTdv1ybo44MlEWxo7VpCXyO1l"; private static String bucketName = "dmddjly";设置文件上传到哪个bucket 以及 该bucket设置的秘钥。
还有设置bucket所选的地区 我选的是华东1(杭州)
2.3UpLoadController
package com.dmdd.javasecuritypractice.controller;
import com.dmdd.javasecuritypractice.util.OSSUtil;
import com.dmdd.javasecuritypractice.util.ResponseResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@RestController
public class UploadController {
@PostMapping("/upload")
public ResponseResult<String> upload(MultipartFile file) throws IOException{
//上传OSS
OSSUtil.upload(file.getInputStream(),file.getOriginalFilename());
//获得url
String url = OSSUtil.getURL(file.getOriginalFilename());
return ResponseResult.ok(url);
}
}
调用工具类方法,实现文件上传。
三. vue脚手架实现图片上传
3.1调用elementui的文件上传功能
<el-form-item label="头像" :label-width="formLabelWidth">
<el-upload
class="avatar-uploader"
action="http://localhost:8080/upload"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="user.icon" :src="user.icon" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</el-form-item>
1. action 是选择图片后将会发送的请求
2.:on-success 成功后执行的事件
3.:before-upload 发送图片前执行的事件,可以进行图片类型 ,大小的限制
3.2两个事件:
//上传图片成功回调
handleAvatarSuccess(res, file) {
console.log(res)
this.user.icon = res.data;
},
//上传前检查
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;
},
最终结果