当前位置 博文首页 > 俺叫啥好嘞的博客:SpringBoot整合阿里云OSS上传文件参考代码

    俺叫啥好嘞的博客:SpringBoot整合阿里云OSS上传文件参考代码

    作者:[db:作者] 时间:2021-09-14 16:26

    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>
    
    

    新建AliyunOSSUtil.java工具类

    /**
     * @date 2020/5/27 13:18
     */
    @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;
        }
    }
    
    

    controller层

    **
     * @author 小四
     * @descibe oss
     * @date 2020/5/27 13:19
     */
    @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;
        }
    }
    
    

    测试界面

    <!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>
    
    

    成功界面

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">