Spring boot上传图片的两种使用方式(阿里OSS存储&本地存储)

这里介绍两种上传存储方式

一、将图片上传到阿里OSS

1.引入依赖


        
            com.aliyun.oss
            aliyun-sdk-oss
            2.8.3
        
        
            org.projectlombok
            lombok
            1.18.4
        
        
            joda-time
            joda-time
            2.9.9
        

2.编写aliyun.properties配置文件

accessKeyId以及accessKeySecret获取参考官方文档:
https://help.aliyun.com/knowledge_detail/48699.html

3.编写AliyunConfig配置类

@Configuration
@PropertySource("aliyun.properties")
@ConfigurationProperties(prefix = "aliyun")
public class AlyunConfig {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    private String urlPrefix;

    @Bean
    public OSS oSSClient() {
        return new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    public String getUrlPrefix() {
        return urlPrefix;
    }

    public void setUrlPrefix(String urlPrefix) {
        this.urlPrefix = urlPrefix;
    }
}

4.编写PicUploadResult

该类用于返回给前端的数据结构定义

public class PicUploadResult {
    // 文件唯一标识
    private String uid;
    // 文件名
    private String name;
    // 状态有:uploading done error removed
    private String status;
    // 服务端响应内容,如:'{"status": "success"}'
    private String response;

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }
}

5.编写PicUploadService

具体的上传逻辑实现,在该类中调用了OSS客户端的API。
 

@Service
public class picUploadService {
    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};
    @Autowired
    private OSS ossClient;
    @Autowired
    private AlyunConfig aliyunConfig;


    public PicUploadResult upload(MultipartFile uploadFile) {
        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
                    type)) {isLegal = true;
                break;
            }
        } // 封装Result对象,并且将文件的byte数组放置到result对象中
        PicUploadResult fileUploadResult = new PicUploadResult();
        if(!isLegal){
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        } // 文件新路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        // 上传到阿里云
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        } 
        fileUploadResult.setStatus("done");
        fileUploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return fileUploadResult;
    }
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + System.currentTimeMillis() +
                RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
    }
}

这里生成图片id为了方便采用的是以当前秒数做id

6.编写PicUploadController

@Controller
public class PicUploadController {

@Autowired
private picUploadService picUploadService;

@RequestMapping("/pic/upload")
    @PostMapping
    @ResponseBody
    public PicUploadResult upload(@RequestParam("file") MultipartFile uploadFile)
            throws Exception {
        return this.picUploadService.upload(uploadFile);
    }
}

启动启动类PicApplication

7.测试

测试工具:Postman

Spring boot上传图片的两种使用方式(阿里OSS存储&本地存储)_第1张图片

注意这里的key一定要与@RequestParam("file") 中的相同

上传文件时报错

显示文件的大小超出了允许的范围。查看了官方文档,原来Spring Boot工程嵌入的tomcat限制了请求的文件大小 

我这里使用的是spring boot2.0

解决办法

在yml文件配置

Spring boot上传图片的两种使用方式(阿里OSS存储&本地存储)_第2张图片

其它Spring boot版本配置可以参考这篇博客https://blog.csdn.net/u010429286/article/details/54381705

最后问题解决 数据正确返回

Spring boot上传图片的两种使用方式(阿里OSS存储&本地存储)_第3张图片

访问name地址查看图片 查看oss中是否有该文件

二、本地文件系统存储

1.编写picUploadFileSystemService

@Service
public class PicUploadFileSystemService {
    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg",
            ".jpeg", ".gif", ".png"};
    public PicUploadResult upload(MultipartFile uploadFile) {
    //校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),
                    type)) {
                isLegal = true;
                break;
            }
        }
        // 封装Result对象,并且将文件的byte数组放置到result对象中
        PicUploadResult fileUploadResult = new PicUploadResult();
        if (!isLegal) {
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        // 文件新路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        // 生成图片的绝对引用地址
        String picUrl = StringUtils.replace(StringUtils.substringAfter(filePath,
                "E:\\code\\test-upload\\images"),
                "\\", "/");
        //访问路径
        fileUploadResult.setName("www.test.image" + picUrl);
        File newFile = new File(filePath);
        // 写文件到磁盘
        try {
            uploadFile.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        //上传失败
            fileUploadResult.setStatus("error");
            return fileUploadResult;
        }
        fileUploadResult.setStatus("done");
        fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return fileUploadResult;
    }
    private String getFilePath(String sourceFileName) {
        String baseFolder = "E:\\code\\test-upload" + File.separator
                + "images";
        Date nowDate = new Date();
        // yyyy/MM/dd
        String fileFolder = baseFolder + File.separator + new
                DateTime(nowDate).toString("yyyy")
                + File.separator + new DateTime(nowDate).toString("MM") +
                File.separator
                + new DateTime(nowDate).toString("dd");
        File file = new File(fileFolder);
        if (!file.isDirectory()) {
        // 如果目录不存在,则创建目录
            file.mkdirs();
        }
        // 生成新的文件名
        String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS")
                + RandomUtils.nextInt(100, 9999) + "." +
                StringUtils.substringAfterLast(sourceFileName, ".");
        return fileFolder + File.separator + fileName;
    }
}

2.编写PicUploadController

@Controller
public class PicUploadController {

@Autowired
private PicUploadFileSystemService picUploadFileSystemService;

@RequestMapping("/pic/upload")
    @PostMapping
    @ResponseBody
    public PicUploadResult upload(@RequestParam("file") MultipartFile uploadFile)
            throws Exception {
        return this.picUploadFileSystemService.upload(uploadFile);
    }
}

3.测试

Spring boot上传图片的两种使用方式(阿里OSS存储&本地存储)_第4张图片

4.搭建nginx进行访问图片

修改nginx.conf文件

Spring boot上传图片的两种使用方式(阿里OSS存储&本地存储)_第5张图片

启动nginx

由于没有域名 这里测试就通过SwitchHosts软件修改本地host文件来实现域名访问

软件下载链接https://download.csdn.net/download/guisu97/11224672

Spring boot上传图片的两种使用方式(阿里OSS存储&本地存储)_第6张图片

访问 

你可能感兴趣的:(项目知识点)