【SpringBoot】-- 实现本地文件/图片上传到服务器生成url地址

avatar
作者
筋斗云
阅读量:1

        在java项目中你可能会有以下需求:用户上传本地图片,然后展示在网页上。本篇文章将使用阿里云oss实现上传图片到oss,oss生成url。

一、准备工作

首先进入阿里云,按如下操作

进入创建页面,修改读写权限为公共读

然后进入bucket,创建AccessKey

创建后,保存好AccessKeyID和AccessKey Secret

二、代码

将以下依赖添加到项目的pom.xml文件中

<dependency>     <groupId>com.aliyun.oss</groupId>     <artifactId>aliyun-sdk-oss</artifactId>     <version>3.15.1</version> </dependency>  <dependency>     <groupId>javax.xml.bind</groupId>     <artifactId>jaxb-api</artifactId>     <version>2.3.1</version> </dependency> <dependency>     <groupId>javax.activation</groupId>     <artifactId>activation</artifactId>     <version>1.1.1</version> </dependency> <!-- no more than 2.3.3--> <dependency>     <groupId>org.glassfish.jaxb</groupId>     <artifactId>jaxb-runtime</artifactId>     <version>2.3.3</version> </dependency>

创建一个工具类,用于配置aliyunoss

添加以下代码:(注意修改)

import com.aliyun.oss.ClientException; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.OSSException; import com.aliyun.oss.model.PutObjectRequest; import com.aliyun.oss.model.PutObjectResult;  import java.io.FileInputStream; import java.io.InputStream;  public class AliOssUtil {      // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。     private static final String ENPOINT = "地区";     // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 //        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();     private static final String ACCESS_KEY_ID="你的ID";     private static final String ACCESS_KEY_SECRT="KEY";     // 填写Bucket名称,例如examplebucket。     private static final String BUCKETNAME = "你的bucket名称";      public static String uploadFile(String objectName, InputStream in) throws Exception {          // 创建OSSClient实例。         OSS ossClient = new OSSClientBuilder().build(ENPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRT);         String url = "";          try {             // 填写字符串。             String content = "Hello OSS,你好世界";              // 创建PutObjectRequest对象。             PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKETNAME, objectName,in);              // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。             // ObjectMetadata metadata = new ObjectMetadata();             // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());             // metadata.setObjectAcl(CannedAccessControlList.Private);             // putObjectRequest.setMetadata(metadata);              // 上传字符串。             PutObjectResult result = ossClient.putObject(putObjectRequest);             //url组成:http://bucket名称.区域节点             url = "https://" + BUCKETNAME + "." + ENPOINT.substring(ENPOINT.lastIndexOf("/")+1)+"/"+objectName;          } catch (OSSException oe) {             System.out.println("Caught an OSSException, which means your request made it to OSS, "                     + "but was rejected with an error response for some reason.");             System.out.println("Error Message:" + oe.getErrorMessage());             System.out.println("Error Code:" + oe.getErrorCode());             System.out.println("Request ID:" + oe.getRequestId());             System.out.println("Host ID:" + oe.getHostId());         } catch (ClientException ce) {             System.out.println("Caught an ClientException, which means the client encountered "                     + "a serious internal problem while trying to communicate with OSS, "                     + "such as not being able to access the network.");             System.out.println("Error Message:" + ce.getMessage());         } finally {             if (ossClient != null) {                 ossClient.shutdown();             }         }         return url;     } }

然后在控制类中使用

@RestController public class FileUploadController {      @PostMapping("/upload")     public Result<String> upload(MultipartFile file) throws Exception {         String originalFilename = file.getOriginalFilename();         //保证文件名字唯一,防止文件覆盖         String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));         String url = AliOssUtil.uploadFile(filename,file.getInputStream());         return Result.success(url);     }  }

三、测试接口

这里使用apifox进行测试

发送请求后,可以看到图片已经存储到oss上,并且返回了地址。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!