1.pom
<!--aliyun-sdk-oss-->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.15.1</version>
</dependency>
2.application.yml
# 阿里云oss
aliyun:
oss:
file:
endpoint: # 域名
bucketname: # 桶
accessKeyId: # accessKeyId
accessKeySecret: # accessKeySecret
3.OssProperties.java
@Data
@Component
public class OssProperties implements InitializingBean {
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;
@Value("${aliyun.oss.file.bucketname}")
private String bucketname;
@Value("${aliyun.oss.file.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.file.accessKeySecret}")
private String accessKeySecret;
public static String ENDPOINT;
public static String BUCKET_NAME;
public static String ASSCESS_KEY_ID;
public static String ASSCESS_KEY_SECRET;
@Override
public void afterPropertiesSet() throws Exception {
ENDPOINT = endpoint;
BUCKET_NAME = bucketname;
ASSCESS_KEY_ID = accessKeyId;
ASSCESS_KEY_SECRET = accessKeySecret;
}
}
4.封装
@Slf4j
public class OssUtil {
private static String endpoint = OssProperties.ENDPOINT;
private static String accessKeyId = OssProperties.ASSCESS_KEY_ID;
private static String accessKeySecret = OssProperties.ASSCESS_KEY_SECRET;
private static String bucketName = OssProperties.BUCKET_NAME;
private static OSSClient ossClient;
/**
* 上传文件到阿里云,并生成url
* @param file
* @return
* @throws IOException
*/
public static String UploadToAliyun(MultipartFile file) throws IOException {
String path = new DateTime().toString("yyyy/MM/dd/");
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".") + 1);
String filedir = path + uuid +"."+suffix;
log.info("------------>文件名称为: " + filedir );
InputStream is = file.getInputStream();
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
String url = "https://%s.%s/%s";;
try {
// 创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(is.available());
objectMetadata.setCacheControl("no-cache");//设置Cache-Control请求头,表示用户指定的HTTP请求/回复链的缓存行为:不经过本地缓存
objectMetadata.setHeader("Pragma", "no-cache");//设置页面不缓存
objectMetadata.setObjectAcl(CannedAccessControlList.PublicRead);
objectMetadata.setContentType(getcontentType(suffix));
objectMetadata.setContentDisposition("inline;filename=" + filedir + "." + suffix);
// 上传文件
ossClient.putObject(bucketName, filedir, is, objectMetadata);
url=String.format(url, bucketName, endpoint, filedir);
log.info("图片地址为="+url);
} catch (IOException e) {
e.printStackTrace();
} finally {
ossClient.shutdown();
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
log.info("上传成功");
}
return url;
}
/**删除图片
* @param key
*/
public static void deletePicture(String key){
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
ossClient.deleteObject(bucketName, key);
ossClient.shutdown();
}
/**
* Description: 判断OSS服务文件上传时文件的contentType
* @param suffix 文件后缀
* @return String HTTP Content-type
*/
public static String getcontentType(String suffix) {
if (suffix.equalsIgnoreCase("bmp")) {
return "image/bmp";
} else if (suffix.equalsIgnoreCase("gif")) {
return "image/gif";
}else if (suffix.equalsIgnoreCase("webp")) {
return "image/webp";
} else if (suffix.equalsIgnoreCase("jpeg") || suffix.equalsIgnoreCase("jpg")) {
return "image/jpeg";
} else if (suffix.equalsIgnoreCase("png")) {
return "image/png";
} else if (suffix.equalsIgnoreCase("html")) {
return "text/html";
} else if (suffix.equalsIgnoreCase("txt")) {
return "text/plain";
} else if (suffix.equalsIgnoreCase("vsd")) {
return "application/vnd.visio";
} else if (suffix.equalsIgnoreCase("pptx") || suffix.equalsIgnoreCase("ppt")) {
return "application/vnd.ms-powerpoint";
} else if (suffix.equalsIgnoreCase("docx") || suffix.equalsIgnoreCase("doc")) {
return "application/msword";
} else if (suffix.equalsIgnoreCase("xml")) {
return "text/xml";
} else if (suffix.equalsIgnoreCase("mp3")) {
return "audio/mp3";
} else if (suffix.equalsIgnoreCase("amr")) {
return "audio/amr";
} else {
return "text/plain";
}
}
}
5.使用
controller
public class FileController {
@ApiOperation("单文件上传")
@PostMapping("/upload")
public ResultVo upload(
MultipartFile file
) throws IOException {
String url= OssUtil.UploadToAliyun(file);
return ResultVo.ok().data("url",url);
}
@ApiOperation("多文件上传")
@PostMapping(value = "/uploads")
public ResultVo fileS(MultipartFile[] files) throws Exception{
List<String> fileList=new ArrayList<>();
for (MultipartFile file:files) { //用foreach处理list列表中的file
fileList.add(OssUtil.UploadToAliyun(file));
}
return ResultVo.ok().data("fileList",fileList);//返回list
}
}