一、案例描述
基于Springboot框架实现一个上传图片到阿里云服务端保存的小案例。
二、准备工作
基于Springboot免费搭载轻量级阿里云OSS数据存储库(将本地文本、照片、视频、音频等上传云服务保存)-CSDN博客
三、代码
新建这两个类:一个是uploadcontroller负责和前端交互,一个aliossutils负责将上传数据与阿里云服务器交互。
UploadController
package com.bytedance.controller; //换成自己的包名
import com.bytedance.pojo.Result;
import com.bytedance.utils.AliOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
@Slf4j
@RestController
public class UploadController {@Autowiredprivate AliOSSUtils aliOSSUtils;@PostMapping("/upload")public Result upload(MultipartFile image) throws Exception {log.info("文件上传,文件名:{}",image.getOriginalFilename());// 调用阿里云oss进行文件类上传String url = aliOSSUtils.upload(image);log.info("文件上传完成,路径为:{}",url);return Result.success(url);}}
AliOSSUtils
package com.bytedance.utils; // 换成自己的包名import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;/*** 阿里云 OSS 工具类*/
@Component
public class AliOSSUtils {private String endpoint = "https://oss-cn-beijing.aliyuncs.com";private String accessKeyId = "LTAI5tPANv8cHYfmuT16U3YV";private String accessKeySecret = "K6OTcJ61K2YQjZFQYi612Hl7ZifFYD";private String bucketName = "mybatiss-tlias";/*** 实现上传图片到OSS*/public String upload(MultipartFile file) throws IOException {// 获取上传的文件的输入流InputStream inputStream = file.getInputStream();// 避免文件覆盖String originalFilename = file.getOriginalFilename();String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));//上传文件到 OSSOSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);ossClient.putObject(bucketName, fileName, inputStream);//文件访问路径String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;// 关闭ossClientossClient.shutdown();return url;// 把上传到oss的路径返回}}
运行:
四、验证
此时还没有图片,我们运行postman仿真:选择本地文件进行提交,我们发现提交成功
再打开OSS管理平台查看:
发现已经提交成功,至此,全篇结束~