图片服务器OSS:跟着宝哥学java:::阿里的oss图片服务器:实现文件上传+文件下载

1:常用的图片服务器

  • hdfs
  • fastdfs
  • oss

2:OSS

  • 通过阿里云实现存储对象来管理文件

注册阿里云

https://oss.console.aliyun.com

开通oss服务

image-20210730122851608

创建bucket

image-20210730123050271

image-20210730123114860

复制外网的endpoint

image-20210730123155703

创建公钥

image-20210730123240134

image-20210730123300472

oss-cn-beijing.aliyuncs.comjava40.oss-cn-beijing.aliyuncs.com
java40
外网访问支持oss-cn-beijing.aliyuncs.comjava43-zhiyou.oss-cn-beijing.aliyuncs.com

AccessKey ID xxxxxxxxxxx

AccessKey Secret xxxxxxxxxxxxxx

复制公钥的id和secret

aliyun.oss.file.keyid=xxxxxxxxxx
aliyun.oss.file.keysecret=xxxxxxxxxxxx

创建springboot项目

  • 导入jar报
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhiyou100.springcloud</groupId>
    <artifactId>test34_oss</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test34_oss</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 阿里云oss依赖 -->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.8.0</version>
        </dependency>
        <!-- 日期工具栏依赖 -->
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.10.10</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
  • 创建实体类:名字随意记录oss需要的所有属性
package com.zhiyou100.entity;

import lombok.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties(prefix = "aliyun.oss.file")
public class ConstantPropertiesUtils{

    private String endpoint;
    private String keyid;
    private String keysecret;
    private String bucketname;

}
  • 注解报错:添加依赖
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
</dependency>
  • 在配置文件中创建aliyun.oss.file前缀的相关属性
#前缀自己定义  但一定要统一和ConfigurationProperties的prefix一致即可
aliyun.oss.file.bucketname=springcloud-java34
aliyun.oss.file.endpoint=oss-cn-beijing.aliyuncs.com
aliyun.oss.file.keyid=LTAI5tE6gfKNuyiUpunks2qx
aliyun.oss.file.keysecret=sHQGu3angXYH5mhbJSK8dDismMxema
  • 创建service
package com.zhiyou100.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.zhiyou100.entity.ConstantPropertiesUtils;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;
import java.util.UUID;

@Service
@Slf4j
public class OssService{

    @Resource
    private ConstantPropertiesUtils constantPropertiesUtils;

    public String uploadFileAvatar(MultipartFile file) {
        //获取oss上传配置文件中的参数
        String bucketName = constantPropertiesUtils.getBucketname();
        String endpoint = constantPropertiesUtils.getEndpoint();
        String keyId = constantPropertiesUtils.getKeyid();
        String keySecret = constantPropertiesUtils.getKeysecret();

        OSS ossClient;
        InputStream inputStream;
        try {
            // 创建OSSClient实例。
            ossClient  = new OSSClientBuilder().build(endpoint, keyId, keySecret);
            // 上传文件流
            inputStream = file.getInputStream();

            //为了使得文件可以重复上传,每次上传的时候需要将文件名进行修改
            String fileName = file.getOriginalFilename();
            log.info("图片上传的名字为:{}",fileName);
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String newFileName = uuid + fileName;

            //获取当前日期,然后以日期和新的文件名组成全路径,使得oss中的文件按照日期进行分类存储
            String date = new DateTime().toString("yyyy/MM/dd");
            String fullFileName = date + "/" + newFileName;
            log.info("图片保存在oss的全路径为:{}",fullFileName);

            //第一个参数Bucket名称 第二个参数 上传到oss文件路径和文件名称
            ossClient.putObject(bucketName, fullFileName, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();
            return "https://"+bucketName+"."+ endpoint+"/"+fullFileName;
        } catch (Exception e) {
            log.error("文件上传失败",e);
            throw new RuntimeException("文件上传oss失败");
        }
    }
    public void downLoadFileAvatar(String yuan, File muDi) {
        //获取oss上传配置文件中的参数
        String bucketName = constantPropertiesUtils.getBucketname();
        String endpoint = constantPropertiesUtils.getEndpoint();
        String keyId = constantPropertiesUtils.getKeyid();
        String keySecret = constantPropertiesUtils.getKeysecret();

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);

// 下载Object到本地文件,并保存到指定的本地路径中。如果指定的本地文件存在会覆盖,不存在则新建。
// 如果未指定本地路径,则下载后的文件默认保存到示例程序所属项目对应本地路径中。
        File muDiFile=new File(muDi,System.currentTimeMillis()+(yuan.substring(yuan.indexOf("."))));
        ossClient.getObject(new GetObjectRequest(bucketName, yuan),muDiFile);
// 关闭OSSClient。
        ossClient.shutdown();
    }
}
  • action
package com.zhiyou100.controller;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.zhiyou100.service.OssService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.HashMap;

@RestController
@RequestMapping("/eduoss")
@CrossOrigin
public class OssController {
    @Resource
    private OssService ossService;

    //上传头像的方法
    @PostMapping("/upload")
    public String uploadOssFile(MultipartFile file) {
        String url = ossService.uploadFileAvatar(file);
        HashMap<String, String> map = new HashMap<>();
        map.put("url",url);
        return map+"上传成功!";
    }
    @GetMapping("/download")
    public String downloadFile(String fileName){
        File muDiDir=new File("d:/oss");
        ossService.downLoadFileAvatar(fileName,muDiDir);
        return "下载完毕!";
    }
}

测试

通过postman测试:文件上传

image-20210730131304289

通过postman测试:文件下载

image-20210730131607009

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用阿里Java SDK 中的 OSSClient 类实现OSS 下载文件。以下是一个简单的代码示例: ```java import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.GetObjectRequest; import com.aliyun.oss.model.OSSObject; import java.io.File; public class OSSDownloader { public static void main(String[] args) { String accessKeyId = "yourAccessKeyId"; String accessKeySecret = "yourAccessKeySecret"; String endpoint = "http://yourEndpoint"; String bucketName = "yourBucketName"; String objectName = "yourObjectName"; String localFilePath = "yourLocalFilePath"; // 创建OSSClient实例 OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); try { // 下载文件到本地 OSSObject ossObject = ossClient.getObject(new GetObjectRequest(bucketName, objectName)); ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File(localFilePath)); ossObject.close(); System.out.println("文件下载成功!"); } catch (Exception ex) { System.out.println("文件下载失败:" + ex.getMessage()); } finally { // 关闭OSSClient ossClient.shutdown(); } } } ``` 其中,需要替换以下变量: - `accessKeyId`:阿里云的 AccessKeyId - `accessKeySecret`:阿里云的 AccessKeySecret - `endpoint`:OSS 服务的 endpoint - `bucketName`:要下载文件所在的 bucket 名称 - `objectName`:要下载文件OSS 中的路径 - `localFilePath`:要保存到本地的文件路径 运行代码后,就可以将 OSS 中指定路径的文件下载到本地指定位置。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值