赞
踩
1.导入架包
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-java-sdk-s3</artifactId>
<version>1.11.347</version>
</dependency>
2.创建工具类
import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.*; import org.springframework.web.multipart.MultipartFile; import java.text.SimpleDateFormat; import java.util.Date; public class S3Utils { //密匙 static final String ACCESS_KEY =""; static final String SECRET_KEY = ""; //储存桶的名称 static final String BUCKET_NAME = ""; //所属地区 //储存路径,不同太在意我的,填你自己想要储存的路径 static final String PATH="scrm"; static final BasicAWSCredentials awsCreds = new BasicAWSCredentials(ACCESS_KEY, SECRET_KEY); static final AmazonS3 s3 = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCreds)) //设置服务器所属地区 .withRegion(Regions.CN_NORTH_1) .build(); /** * 上传到文件返回一个文件储存后的路径 * @param multipartFile * @return * @throws Exception */ public static String uploadFile(MultipartFile multipartFile,String bizPath) { if (multipartFile.isEmpty()) { return "文件为空"; } Date date = new Date(); SimpleDateFormat formatter_yyyy = new SimpleDateFormat("yyyy"); SimpleDateFormat formatter_MM = new SimpleDateFormat("MM"); //在随机名前加上年月 String s3FilePath =bizPath + "/" +formatter_yyyy.format(date) + "/" + formatter_MM.format(date) + "/" + multipartFile.getOriginalFilename(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType(multipartFile.getContentType()); metadata.setContentLength(multipartFile.getSize()); try { //开始上传文件 //1.不支持公网访问 //s3.putObject(BUCKET_NAME, s3FilePath, multipartFile.getInputStream(), metadata) //2.支付公网访问 PutObjectResult putObjectResult=s3.putObject(new PutObjectRequest(BUCKET_NAME, s3FilePath, multipartFile.getInputStream(), metadata) .withCannedAcl(CannedAccessControlList.PublicRead)); putObjectResult.getContentMd5(); System.err.println("上传完成__文件位置为" + putObjectResult); } catch (Exception e) { e.printStackTrace(); } //返回文件位置 return "https://houyu-s3.s3.cn-north-1.amazonaws.com.cn/"+s3FilePath; } /** * 用过文件路径获取文件下载地址 * @param path * @return */ public static String downloadFile(String path){ try { GeneratePresignedUrlRequest httpRequest = new GeneratePresignedUrlRequest(BUCKET_NAME, path); return s3.generatePresignedUrl(httpRequest).toString()+path; }catch (Exception e){ e.printStackTrace(); } return "获取失败"; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。