SpringBoot整合阿里云OSS上传文件

x33g5p2x  于2021-12-23 转载在 Spring  
字(5.0k)|赞(0)|评价(0)|浏览(293)

一、需求分析

文件上传是一个非常常见的功能,就是通过IO流将文件写到另外一个地方,这个地方可以是项目下的某个文件夹里,或者是本地电脑某个盘下面,还可以是云服务OSS里面,这里就是我要讲到的OSS,我写的是基于阿里云的。

二:环境搭建

我这里是用的Springboot.Thymeleaf插件,为了在html页面实现文件上传功能。

1、首先开通阿里云OSS存储,这里不多说了。

2、创建一个Bucket

这个bucket名称是等下参数里面要用到的。区域可以选择你那边的区域。

3、创建好之后返回刚才的页面,点击Access Key,来获取accessKeyId、accessKeySecret这两个参数

4、Maven依赖(Thymeleaf、OSS)

<!-- 阿里云OSS-->
      <dependency>
          <groupId>com.aliyun.oss</groupId>
          <artifactId>aliyun-sdk-oss</artifactId>
          <version>2.4.0</version>
      </dependency>
      <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.1</version>
      </dependency>

5、新建一个UpLoadController.java

**
 * @descibe oss
 */
@Controller
public class UpLoadController {
    private static final String TO_PATH = "upload";
    private static final String RETURN_PATH = "success";

    @Autowired
    private AliyunOSSUtil aliyunOSSUtil;

    @RequestMapping("/toUpLoadFile")
    public String toUpLoadFile() {
        return TO_PATH;
    }

    /** * 文件上传 */
    @RequestMapping(value = "/uploadFile")
    public String uploadBlog(@RequestParam("file") MultipartFile file) {
        String filename = file.getOriginalFilename();
        System.out.println(filename + "==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.transferTo(newFile);
                    // 上传到OSS
                    String uploadUrl = aliyunOSSUtil.upLoad(newFile);
                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return RETURN_PATH;
    }
}

6、新建AliyunOSSUtil.java

/** * @descibe oss */
@Component
public class AliyunOSSUtil {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);

    /** * 上传文件 */
    public String upLoad(File file) {
        logger.info("------OSS文件上传开始--------" + file.getName());
        String endpoint = "你的endpoint ";    
        //这里endpoint 在你的bucket列表->点击你的bucket->点击概览中间就有,下面有截图
        System.out.println("获取到的Point为:" + endpoint);
        String accessKeyId = "你的accessKeyId ";    //accessKeyId 、accessKeySecret 上面有说到哪里获取
        String accessKeySecret = "你的accessKeySecret ";
        String bucketName = "你的bucketName ";  //刚才新建的bucket名称
        String fileHost = "你的fileHost ";   //在刚才新建的bucket下面新建一个目录,这就是那个目录的名称
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());

        // 判断文件
        if (file == null) {
            return null;
        }
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            // 判断容器是否存在,不存在就创建
            if (!client.doesBucketExist(bucketName)) {
                client.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                client.createBucket(createBucketRequest);
            }
            // 设置文件路径和名称
            String fileUrl = fileHost + "/" + (dateStr + "/" + UUID.randomUUID().toString().replace("-", "") + "-" + file.getName());
            // 上传文件
            PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));
            // 设置权限(公开读)
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if (result != null) {
                logger.info("------OSS文件上传成功------" + "https://makeromance.oss-cn-hangzhou.aliyuncs.com/" + fileUrl);
            }
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (ClientException ce) {
            logger.error(ce.getErrorMessage());
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }
        return null;
    }
}

获取endpoint:

7、新建upload.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>【基于OSS的上传文件页面】</title>
    <style type="text/css"> * { margin: 0; padding: 0; } #group { position: absolute; left: 580px; } #submit { position: absolute; top: 140px; left: 580px; } </style>
</head>
<body>
<div align="center">
    <h2 style="color:orangered;">基于OSS的上传文件页面</h2>
</div>
<br/>
<form action="/uploadFile" enctype="multipart/form-data" method="post">
    <div class="form-group" id="group">
        <label for="exampleInputFile">File input</label>
        <input type="file" id="exampleInputFile" name="file">
    </div>
    <button type="submit" class="btn btn-default" id="submit">上传</button>
</form>
</body>
</html>

success.html:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>【文件上传成功页面】</title>
</head>
<body>
<div align="center">
    <h5>上传成功</h5>
    <img src="https://makeromance.oss-cn-hangzhou.aliyuncs.com/langmanji/2020-05-27/3c7a040df2ad4f6ca5f6da47373c8773-xiazaierweima.jpg"/>
</div>
</body>
</html>

三、运行项目

选择一个文件点击上传:

提示上传成功,我们看下控制台:

输出的是我们文件上传的路径,然后我们看下我们阿里云OSS存储里面有没有数据:

发现已经有了,这就是一个SpringBoot基于阿里云OSS上传文件的例子。

相关文章

微信公众号

最新文章

更多