目录
依赖添加
- <!--阿里云OSS-->
- <dependency>
- <groupId>com.aliyun.oss</groupId>
- <artifactId>aliyun-sdk-oss</artifactId>
- <version>2.8.3</version>
- </dependency>
在application.yml中添加配置信息:
- #OSS配置
- oss:
- #带有地域节点的请求地址
- endpoint: oss-cn-beijing.aliyuncs.com
- #阿里云用户id
- accessKey: XXXXXXRnmzC2aafr9KXXXXXX
- #阿里云用户密码
- secretKey: XXXXXXFBaNzv85rqiks804mGXXXXXX
- #阿里云存储空间名
- bucketname: home
- #阿里服务器的域名
- fileHost: http://home.oss-cn-beijing.aliyuncs.com/
- #上传文件路径
- filePath: upload
实体类:
- import lombok.Data;
- /**
- * @author CYY
- * @date 2022/4/15 16:52
- */
- @Data
- public class OssData {
- /**
- * 服务器域名
- */
- private String host;
- /**
- * 上传文件路径
- */
- private String path;
- /**
- * 上传文件名
- */
- private String fileName;
- }
OSS配置类:
- import com.aliyun.oss.OSSClient;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- /**
- * OSS配置类
- *
- * @author CYY
- * @date 2022/4/15 16:20
- */
- @Configuration
- public class OSSClientConfig {
- @Value("${oss.endpoint}")
- String endpoint;
- @Value("${oss.accessKey}")
- String accessKeyId;
- @Value("${oss.secretKey}")
- String accessKeySecret;
- // 创建OSS客户端Bean
- @Bean
- public OSSClient getOSSClient() {
- return new OSSClient(endpoint, accessKeyId, accessKeySecret);
- }
- }
OSSUtil工具类:
- import com.aliyun.oss.ClientException;
- import com.aliyun.oss.OSSClient;
- import com.aliyun.oss.OSSException;
- import com.aliyun.oss.model.CannedAccessControlList;
- import com.aliyun.oss.model.CreateBucketRequest;
- import com.aliyun.oss.model.PutObjectRequest;
- import com.aliyun.oss.model.PutObjectResult;
- import lombok.extern.log4j.Log4j2;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Component;
- import javax.annotation.Resource;
- import java.io.File;
- /**
- * 阿里OSS工具类
- *
- * @author CYY
- * @date 2022/4/15 16:23
- */
- @Component
- @Log4j2
- public class AliyunOSSUtil {
- @Value("${oss.bucketname}")
- String bucketName;
- @Resource
- private OSSClient client;
- /**
- * 上传文件
- */
- public String upLoad(File file, String fileUrl) {
- log.info("------OSS文件上传开始--------" + file.getName());
- // 判断文件是否为空
- if (file == null) {
- return null;
- }
- try {
- // 判断容器是否存在,不存在就创建
- if (!client.doesBucketExist(bucketName)) {
- client.createBucket(bucketName);
- CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
- createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
- client.createBucket(createBucketRequest);
- // 设置权限(公开读)
- client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
- }
- // 上传文件
- PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
- if (result != null) {
- log.info("------OSS文件上传成功------" + fileUrl);
- return fileUrl;
- }
- } catch (OSSException oe) {
- log.error(oe.getMessage());
- } catch (ClientException ce) {
- log.error(ce.getErrorMessage());
- } finally {
- }
- return null;
- }
- }
OSS上传接口类:
- import org.springframework.web.multipart.MultipartFile;
- /**
- * @author CYY
- * @date 2022/4/15 16:42
- */
- public interface OssUploadService {
- /**
- * 上传文件
- * @param file
- * @return
- */
- String upload(MultipartFile file);
- }
OSS上传接口实现类:
- import jnpf.service.OssUploadService;
- import jnpf.utils.AliyunOSSUtil;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Service;
- import org.springframework.web.multipart.MultipartFile;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- /**
- * @author CYY
- * @date 2022/4/15 16:43
- */
- @Service
- public class OssUploadServiceImpl implements OssUploadService {
- private final AliyunOSSUtil aliyunOSSUtil;
- @Autowired
- public OssUploadServiceImpl(AliyunOSSUtil aliyunOSSUtil){
- this.aliyunOSSUtil = aliyunOSSUtil;
- }
- @Value("${oss.filePath}")
- private String filePath;
- @Override
- public String upload(MultipartFile file) {
- // 返回客户端文件系统中的原始文件名
- String fileName = file.getOriginalFilename();
- System.out.println(fileName);
- try{
- if (file != null) {
- // 判定文件名是否为 ""
- if (!"".equals(fileName.trim())) {
- File newFile = new File(fileName);
- FileOutputStream os = new FileOutputStream(newFile);
- // 以字节数组的形式返回文件的内容,再输出到文件输出流中
- os.write(file.getBytes());
- os.close();
- // 将接受的文件传输到给定的目标文件 file-->newFile
- file.transferTo(newFile);
- // 根据不同文件 类型/日期 生成不同的文件夹
- Date date = new Date();
- //String datePath = DateUtils.formatDateByStyle(date, DatePattern.CN_DATE_BASIC_STYLE4.getDatePattern());
- String datePath = getCode().toString();
- String timeStamp = String.valueOf(System.currentTimeMillis());
- fileName = timeStamp + fileName.substring(fileName.lastIndexOf("."));
- String path;
- if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg") || fileName.endsWith(".png")) {
- // images
- path = filePath + "/images/" + datePath + "/" + fileName;
- } else {
- path = filePath + "/other/" + datePath + "/" + fileName;
- }
- // 上传到OSS
- String uploadUrl = aliyunOSSUtil.upLoad(newFile, path);
- newFile.delete();
- if (uploadUrl != null) {
- return uploadUrl;
- }
- }
- }
- }catch (Exception e){
- e.printStackTrace();
- }
- return null;
- }
- /**
- * 生成编号
- *
- * @return code
- */
- private static Long getCode() {
- //生成当前时间戳的ID
- SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
- String newDate = sdf.format(new Date());
- //生成5位随机数
- int randomNum = (int) ((Math.random() * 9 + 1) * 10000);
- String result = String.valueOf(randomNum);
- String s = newDate + result;
- Long code = Long.parseLong(s);
- return code;
- }
- }
OSS上传控制类:
- import io.swagger.annotations.Api;
- import io.swagger.annotations.ApiOperation;
- import jnpf.base.ActionResult;
- import jnpf.entity.OssData;
- import jnpf.service.OssUploadService;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.web.bind.annotation.*;
- import org.springframework.web.multipart.MultipartFile;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- /**
- * 阿里云OSS
- *
- * @author CYY
- * @date 2022/4/15 16:53
- */
- @Api(tags = "阿里云OSS",value = "阿里云OSS")
- @RestController
- @RequestMapping("/api/file/oss")
- public class OssUploadController {
- @Value("${oss.fileHost}")
- String fileHost;
- @Autowired
- private OssUploadService ossUploadService;
- /**
- * 获取服务器的ip地址
- *
- * @return
- */
- @ApiOperation("获取服务器的ip地址")
- @GetMapping("getHost")
- public ActionResult getHost() {
- OssData ossData = new OssData();
- ossData.setHost(fileHost);
- return ActionResult.success(ossData);
- }
- /**
- * oss上传文件(单个文件上传)
- *
- * @param file
- * @return
- */
- @ApiOperation("oss上传文件(单个文件上传)")
- @PostMapping("fileUpload")
- public ActionResult fileUpload(@RequestParam("file") MultipartFile file) {
- OssData ossData = new OssData();
- // 上传文件返回url
- String url = ossUploadService.upload(file);
- String fileName=url.substring(url.lastIndexOf("/")+1);
- if (url != null) {
- ossData.setHost(fileHost);
- ossData.setPath(fileHost + url);
- ossData.setFileName(fileName);
- return ActionResult.success(ossData);
- } else {
- return ActionResult.fail(300, "上传失败");
- }
- }
- /**
- * oss多文件上传
- *
- * @param files
- * @return
- */
- @ApiOperation("oss多文件上传")
- @PostMapping("filesUpload")
- public ActionResult filesUpload(@RequestParam("file") List<MultipartFile> files) {
- OssData ossData = new OssData();
- Map<String, String> urls = new HashMap<>();
- for (MultipartFile file : files) {
- String url = ossUploadService.upload(file);
- if (url != null) {
- String fileName = file.getOriginalFilename();
- url = fileHost + url;
- urls.put(fileName, url);
- } else {
- ossData.setFileName(file.getOriginalFilename());
- ossData.setPath(fileHost + url);
- return ActionResult.fail(100, ossData, "上传失败");
- }
- }
- return ActionResult.success(urls);
- }
- /**
- * oss 分俩个file,多文件上传
- *
- * @param file01
- * @param file02
- * @return
- */
- @ApiOperation("oss 分俩个file,多文件上传")
- @PostMapping("filesUploadMore")
- public ActionResult filesUploadMore(@RequestParam("file01") List<MultipartFile> file01, @RequestParam("file02") List<MultipartFile> file02) {
- OssData ossData = new OssData();
- Map<String, String> urls = new HashMap<>();
- for (MultipartFile file : file01) {
- try {
- String url = ossUploadService.upload(file);
- if (url != null) {
- String fileName = file.getOriginalFilename();
- url = fileHost + url;
- urls.put(fileName, url);
- } else {
- ossData.setFileName(file.getOriginalFilename());
- return ActionResult.fail(100, ossData, "上传失败");
- }
- } catch (Exception e) {
- e.printStackTrace();
- ossData.setFileName(file.getOriginalFilename());
- return ActionResult.fail(100, ossData, "上传失败");
- }
- }
- for (MultipartFile file : file02) {
- try {
- String url = ossUploadService.upload(file);
- if (url != null) {
- String fileName = file.getOriginalFilename();
- url = fileHost + url;
- urls.put(fileName, url);
- } else {
- ossData.setFileName(file.getOriginalFilename());
- return ActionResult.fail(100, ossData, "上传失败");
- }
- } catch (Exception e) {
- e.printStackTrace();
- ossData.setFileName(file.getOriginalFilename());
- return ActionResult.fail(100, ossData, "上传失败");
- }
- }
- return ActionResult.success(urls);
- }
- }
工具类:
- import com.fasterxml.jackson.annotation.JsonInclude;
- import io.swagger.annotations.ApiModelProperty;
- import jnpf.base.vo.PageListVO;
- import jnpf.base.vo.PaginationVO;
- import lombok.Data;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- /**
- * @author CYY
- * @date 2022/4/15 16:43
- */
- @Data
- @JsonInclude(JsonInclude.Include.NON_NULL)
- public class ActionResult<T> {
- @ApiModelProperty("状态码")
- private Integer code;
- @ApiModelProperty("返回信息")
- private String msg;
- @ApiModelProperty("返回数据")
- private T data;
- public static ActionResult success() {
- ActionResult jsonData = new ActionResult();
- jsonData.setCode(200);
- jsonData.setMsg("Success");
- return jsonData;
- }
- public static ActionResult success(String msg) {
- ActionResult jsonData = new ActionResult();
- jsonData.setCode(200);
- jsonData.setMsg(msg);
- return jsonData;
- }
- public static ActionResult success(Object rows, PageModel pageModel) {
- ActionResult jsonData = new ActionResult();
- Map<String, Object> map = new HashMap<>(16);
- map.put("page", pageModel.getPage());
- map.put("records", pageModel.getRecords());
- map.put("rows", rows);
- map.put("total", pageModel.getTotal());
- jsonData.setData(map);
- jsonData.setCode(200);
- jsonData.setMsg("Success");
- return jsonData;
- }
- public static ActionResult success(Object object) {
- ActionResult jsonData = new ActionResult();
- jsonData.setData(object);
- jsonData.setCode(200);
- jsonData.setMsg("Success");
- return jsonData;
- }
- public static <T> ActionResult page(List<T> list, PaginationVO pagination) {
- ActionResult jsonData = new ActionResult();
- PageListVO<T> vo = new PageListVO<>();
- vo.setList(list);
- vo.setPagination(pagination);
- jsonData.setData(vo);
- jsonData.setCode(200);
- jsonData.setMsg("Success");
- return jsonData;
- }
- public static ActionResult success(String msg, Object object) {
- ActionResult jsonData = new ActionResult();
- jsonData.setData(object);
- jsonData.setCode(200);
- jsonData.setMsg(msg);
- return jsonData;
- }
- public static ActionResult fail(Integer code, String message) {
- ActionResult jsonData = new ActionResult();
- jsonData.setCode(code);
- jsonData.setMsg(message);
- return jsonData;
- }
- public static ActionResult fail(Integer code, Object object, String message) {
- ActionResult jsonData = new ActionResult();
- jsonData.setCode(code);
- jsonData.setData(object);
- jsonData.setMsg(message);
- return jsonData;
- }
- public static ActionResult fail(String msg, String data) {
- ActionResult jsonData = new ActionResult();
- jsonData.setMsg(msg);
- jsonData.setData(data);
- return jsonData;
- }
- public static ActionResult fail(String msg) {
- ActionResult jsonData = new ActionResult();
- jsonData.setMsg(msg);
- jsonData.setCode(400);
- return jsonData;
- }
- }
- import lombok.Data;
- import java.util.List;
- /**
- * @author CYY
- * @date 2022/4/15 16:43
- */
- @Data
- public class PageListVO<T> {
- private List<T> list;
- PaginationVO pagination;
- }
- import lombok.Data;
- /**
- * @author CYY
- * @date 2022/4/15 16:43
- */
- @Data
- public class PaginationVO {
- private Long currentPage;
- private Long pageSize;
- private Integer total;
- }
转自:https://blog.csdn.net/HellocWood/article/details/124836732
标签:文件,return,String,OSS,ActionResult,jsonData,file,import,上传 From: https://www.cnblogs.com/tiancai/p/17584462.html