SpringBoot整合阿里云OSS存储服务

摘要:OSS可用于图片、音视频、日志等海量文件的存储。各种终端设备、Web网站程序、移动应用可以直接向OSS写入或读取数据,非常方便。本篇文章介绍如何在java的SpringBoot项目中,整个使用OSS服务,spring 项目也可以参考。

主要步骤如下:

前提是开通了阿里云OSS服务,然后;

1.引入依赖

2.获取关键参数,如endpoint,accessKeyId等,这个进入阿里云OSS控制台即可获取

3.建一个文件上传工具类

4.调用工具类,上传文件

1.pom.xml

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

2.配置文件

注意:为了以后的拓展性,代码和配置解耦,我这里会专门建一个配置文件,然后在使用时直接从配置类中获取,而不是写死在java代码中。所以2,3两步不是必须的,作用只是规范的使用相关配置参数,若觉得麻烦,学习时,可直接在java代码中写死。application.properties  这里是我定义的一些必要常量

#OSS
java4all.file.endpoint=oss-cn-shanghai.aliyuncs.com 不同的服务器,地址不同
java4all.file.keyid=去OSS控制台获取
java4all.file.keysecret=去OSS控制台获取
java4all.file.bucketname1=java4all-file 这个自己创建bucket时的命名,控制台创建也行,代码创建也行
java4all.file.filehost=blog 文件路径,我这里是blog

3.ConstantProperties.java

这是我定义的常量类,读取配置文件application.properties中的配置,定义为常量,方便使用

package com.java4all.config;
 
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
 
/**
 * Created by lightClouds917
 * Date 2018/1/16
 * Description:配置文件配置项
 */
@Component
public class ConstantProperties{
 
    @Value("${java4all.file.endpoint}")
    private String java4all_file_endpoint;
 
    @Value("${java4all.file.keyid}")
    private String java4all_file_keyid;
 
    @Value("${java4all.file.keysecret}")
    private String java4all_file_keysecret;
 
    @Value("${java4all.file.filehost}")
    private String java4all_file_filehost;
 
    @Value("${java4all.file.bucketname1}")
    private String java4all_file_bucketname1;
 
 
    public static String JAVA4ALL_END_POINT;
    public static String JAVA4ALL_ACCESS_KEY_ID;
    public static String JAVA4ALL_ACCESS_KEY_SECRET;
    public static String JAVA4ALL_BUCKET_NAME1;
    public static String JAVA4ALL_FILE_HOST;
 
    @PostConstruct
    private void initial(){
        JAVA4ALL_END_POINT = java4all_file_endpoint;
        JAVA4ALL_ACCESS_KEY_ID = java4all_file_keyid;
        JAVA4ALL_ACCESS_KEY_SECRET = java4all_file_keysecret;
        JAVA4ALL_FILE_HOST = java4all_file_filehost;
        JAVA4ALL_BUCKET_NAME1 = java4all_file_bucketname1;
    }
}

上传阿里云工具类:

package com.example.demo.common;
import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.Random;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
/**
 * Created by Administrator on 2018/1/27 0027.
 */
public class OSSClientUtil {
    Log log = LogFactory.getLog(OSSClientUtil.class);
    // endpoint以杭州为例,其它region请按实际情况填写
    protected static String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
    protected static String accessKeyId  = "你的accessKeyId";
    protected static String accessKeySecret  = "你的accessKeySecret";
    protected static String bucketName  = "weishang-fc";
    //文件存储目录
    private String filedir = "imgupload/";

    private OSSClient ossClient;

    public OSSClientUtil() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 初始化
     */
    public void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 销毁
     */
    public void destory() {
        ossClient.shutdown();
    }

    /**
     * 上传图片
     *
     * @param url
     */
    public void uploadImg2Oss(String url) throws Exception {
        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            this.uploadFile2OSS(fin, split[split.length - 1]);
        } catch (FileNotFoundException e) {
            throw new Exception("图片上传失败01");
        }
    }


    public String uploadImg2Oss(MultipartFile file) throws Exception {
        if (file.getSize() > 1024 * 1024) {
            throw new Exception("上传图片大小不能超过1M!");
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name);
            return name;
        } catch (Exception e) {
            throw new Exception("图片上传失败02");
        }
    }

    /**
     * 获得图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return this.getUrl(this.filedir + split[split.length - 1]);
        }
        return null;
    }

    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param instream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFile2OSS(InputStream instream, String fileName) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }
}

service:(这个根据需要,也可以省略直接在controller里面写)

@Service
public class UpDownServiceImpl {

    private OSSClientUtil ossClient=new OSSClientUtil();
    public String updateHead(MultipartFile file, long userId) throws Exception {
        if (file == null || file.getSize() <= 0) {
            throw new Exception("头像不能为空");
        }
        String name = ossClient.uploadImg2Oss(file);
        String imgUrl = ossClient.getImgUrl(name);
        //userDao.updateHead(userId, imgUrl);//只是本地上传使用的
        return imgUrl;
    }
}

controller:

@Controller
@RequestMapping("/user")
public class UserController {

//处理文件上传
    @RequestMapping(value="/testuploadimg", method = RequestMethod.POST)
    @ResponseBody
    /*public  String uploadImg(@RequestParam("file") MultipartFile file,
                             HttpServletRequest request) {*/
        public Map<String, Object> headImgUpload(HttpServletRequest request,@RequestParam("file")MultipartFile file) {
            Map<String, Object> value = new HashMap<String, Object>();
            value.put("success", true);
            value.put("errorCode", 0);
            value.put("errorMsg", "");
            try {
                String head = upDownServiceImpl.updateHead(file, 4);//此处是调用上传服务接口,4是需要更新的userId 测试数据。
                value.put("data", head);
            } catch (IOException e) {
                e.printStackTrace();
                value.put("success", false);
                value.put("errorCode", 200);
                value.put("errorMsg", "图片上传失败");
            } catch (Exception e) {
                e.printStackTrace();
            }
        return value; 
    }
}

 前端页面:

<!--文件上传-->
<div style="border: solid 1px">
  <form enctype="multipart/form-data" method="post" th:action= "@{/user/testuploadimg}">图片<input type="file" name="file"/>
    <input type="submit" value="上传"/>
  </form>
</div>

我自己捣鼓了半天的小坑:
bucket.oss-cn-hangzhou.aliyuncs.com 不要填类似这样的
应该直接填Endpoint,如:
oss-cn-shanghai.aliyuncs.com
我一直写成:

// endpoint以杭州为例,其它region请按实际情况填写
    protected static String endpoint = "http://weishang-fc.oss-cn-shanghai.aliyuncs.com";
    protected static String accessKeyId  = "xx";
    protected static String accessKeySecret  = "xx";
    protected static String bucketName  = "weishang-fc"; 

正确应该是这样:

   // endpoint以杭州为例,其它region请按实际情况填写
    protected static String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
    protected static String accessKeyId  = "xx";
    protected static String accessKeySecret  = "xx";
    protected static String bucketName  = "weishang-fc"; 

这里只是简单的单个图片/文件的上传,记录下来,方便下次使用。

猜你喜欢

转载自blog.csdn.net/qq_19734597/article/details/82862120