SpringBoot 上传头像到阿里云

本文档详细介绍了如何在SpringBoot项目中整合阿里云OSS服务,包括引入依赖、配置属性、创建常量工具类以及实现图片上传的控制器。用户通过上传头像表单,将图片发送到阿里云OSS,并将上传后的URL保存至用户信息中。
摘要由CSDN通过智能技术生成

1、导入依赖 - pom.xml

<!-- 阿里云对象存储 -->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.11.1</version>
</dependency>

<!-- 日期工具栏依赖 -->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.8</version>
</dependency>

2、写配置 - application.properties

#阿里云 OSS
aliyun.oss.file.endpoint=你的 oss-cn-shenzhen.aliyuncs.com
aliyun.oss.file.keyid=你的 access-key
aliyun.oss.file.keysecret=你的 secret-key:
aliyun.oss.file.bucketname=你的桶名

3、配置常量工具类 - OssConstantUtils

package com.jili20.util;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author bing  @create 2020/11/30-4:10 下午
 */
@Component
public class OssConstantUtils implements InitializingBean {

    //读取配置文件内容
    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.keyid}")
    private String keyId;

    @Value("${aliyun.oss.file.keysecret}")
    private String keySecret;

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketName;

    //定义公开静态常量
    public static String END_POIND;
    public static String ACCESS_KEY_ID;
    public static String ACCESS_KEY_SECRET;
    public static String BUCKET_NAME;

    @Override
    public void afterPropertiesSet() throws Exception {
        END_POIND = endpoint;
        ACCESS_KEY_ID = keyId;
        ACCESS_KEY_SECRET = keySecret;
        BUCKET_NAME = bucketName;
    }
}

4、上传头像控制器- UserController

package com.jili20.controller;
。。。。。。
/**
 * @author bing  @create 2020/11/30-11:02 下午
 */
@Controller
public class UserController implements CommunityConstant {

    private static final Logger logger = (Logger) LoggerFactory.getLogger(UserController.class);

		@Autowired
    private UserService userService;

    @Autowired // 当前用户
    private HostHolder hostHolder;

    // 用户设置页面
    @LoginRequired // 自定义注解,登录才能访问
    @GetMapping("/user/setting")
    public String getSettingPage() {
        return "/site/setting";
    }

    // 上传头像到阿里云OSS
    @LoginRequired // 自定义注解,登录才能访问
    @PostMapping("/user/upload")
    public String uploadHeader(MultipartFile headerImage, Model model, RedirectAttributes attr) {
        if (headerImage == null) {
            model.addAttribute("error", "您还没有选择图片!");
            return "/site/setting";
        }

        // 工具类获取值
        String endpoint = OssConstantUtils.END_POIND;
        String accessKeyId = OssConstantUtils.ACCESS_KEY_ID;
        String accessKeySecret = OssConstantUtils.ACCESS_KEY_SECRET;
        String bucketName = OssConstantUtils.BUCKET_NAME;

        try {
            // 创建OSS实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            //获取上传文件输入流
            InputStream inputStream = headerImage.getInputStream();
            //获取文件名称
            String fileName = headerImage.getOriginalFilename();

            //1 在文件名称里面添加随机唯一的值
            // replaceAll 把所有 - 替换成 ""
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            // yuy76t5rew01.jpg
            fileName = uuid + fileName;

            //2 把文件按照日期进行分类
            //获取当前日期(用导入依赖的工具类)
            //   2019/11/12
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //拼接
            //  2019/11/12/ewtqr313401.jpg
            fileName = datePath + "/" + fileName;

            //调用oss方法实现上传
            //第一个参数  Bucket名称
            //第二个参数  上传到oss文件路径和文件名称   aa/bb/1.jpg
            //第三个参数  上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();
						// 获取当前用户
            User user = hostHolder.getUser();

            //把上传之后文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            //  https://edu-guli-1010.oss-cn-beijing.aliyuncs.com/01.jpg
            String headerUrl = "https://" + bucketName + "." + endpoint + "/" + fileName;

            int rows = userService.updateHeader(user.getId(), headerUrl);

            if (rows > 0) {
                // 重定向消息提示
                attr.addFlashAttribute("uploadMsg", "上传头像成功");
            }
            return "redirect:/user/setting";
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

5、用户设置页面上传头像表单 - templates/site/setting.html

<!-- 上传头像至阿里云OSS -->
<form class="mt-5" method="post" enctype="multipart/form-data" th:action="@{/user/upload}">
    <div class="form-group row mt-4">
        <label for="head-image" class="col-sm-2 col-form-label text-right">选择头像:</label>
        <div class="col-sm-10">
            <div class="custom-file">
                <input type="file" th:class="|custom-file-input ${error!=null?'is-invalid':''}|"
                       id="head-image" name="headerImage" lang="es" required="">
                <label class="custom-file-label" for="head-image" data-browse="文件">选择一张图片</label>
                <div class="invalid-feedback" th:text="${error}">
                    该账号不存在!
                </div>
            </div>
        </div>
    </div>
    <div class="form-group row mt-4">
        <div class="col-sm-2"></div>
        <div class="col-sm-10 text-center">
            <button type="submit" class="btn btn-info text-white form-control">立即上传</button>
        </div>
    </div>
</form>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值