前言
Amazon文件服务器的使用,本章之记录文件的上传和下载。
pom依赖
首先添加依赖
<dependency> <groupId>com.amazonaws</groupId> <artifactId>aws-java-sdk-s3</artifactId> <version>1.11.336</version> </dependency>
正文
提供个工具类
public class FileUtils { // 【你的 access_key】 static final String AWS_ACCESS_KEY = "*********"; // 【你的 aws_secret_key】 static final String AWS_SECRET_KEY = "*********************"; // 储存桶的名称 static final String BUCKET_NAME = "app-file-upload"; // 设置服务器所属地区 static final Regions REGION = Regions.DEFAULT_REGION; // 储存路径 static final String PATH = "uploadExcel"; static final BasicAWSCredentials awsCreds = new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY); static final AmazonS3 s3 = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(awsCreds)).withRegion(REGION).build(); @Autowired protected HttpServletRequest request; @Autowired protected HttpServletResponse response; /** * 上传到文件返回一个文件储存后的路径 * * @param multipartFile * @return * @throws IOException * @throws SdkClientException * @throws AmazonServiceException * @throws Exception */ public static String uploadFileToS3(MultipartFile multipartFile, String type) throws AmazonServiceException, SdkClientException, IOException { if (multipartFile.isEmpty()) { return "文件为空"; } String dateString = DateUtils.convertToDate(LocalDate.now()); long time = System.currentTimeMillis(); // 拼接下文件路径,为了不会出现文件覆盖现象,加上时间戳 String s3FilePath = PATH + "/" + type + "/" + dateString + "/" + time + "/" + multipartFile.getOriginalFilename(); ObjectMetadata metadata = new ObjectMetadata(); metadata.setContentType(multipartFile.getContentType()); metadata.setContentLength(multipartFile.getSize()); // 开始上传文件 s3.putObject(BUCKET_NAME, s3FilePath, multipartFile.getInputStream(), metadata); // 返回文件位置 return s3FilePath; } /** * 用文件路径获取文件下载地址 * * @param path * @return */ public static String getDownloadFileFromS3(String path) { return s3.generatePresignedUrl(new GeneratePresignedUrlRequest(BUCKET_NAME, path)).toString(); } /** * 获取S3Object对象 * * @param path * @return */ public static S3Object getS3Object(String path) { S3Object s3Object = s3.getObject(BUCKET_NAME, path); return s3Object; } }
S3Object 对象中有输入流,可以使用创建文件。