SpringBoot整合AWS OSS 文件上传

Amazon S3 Glacier文件上传
官方文档:
https://docs.aws.amazon.com/zh_cn/amazonglacier/latest/dev/introduction.html
https://docs.aws.amazon.com/zh_cn/sdk-for-java/v2/developer-guide/setup-install.html

1.下载demo
(本文中的上传类并未使用demo中的代码,demo仅供参考)

https://github.com/awslabs/aws-java-sample.git
打开demo查看README.txt
在这里插入图片描述这里说明一下,这是aws oss 上传文件的安全凭证,可在aws控制台获取参数值,创建的目录为:

~/.aws/credentials on Linux, macOS, or Unix
C:\Users\USERNAME.aws\credentials on Windows

具体可参考:https://blog.csdn.net/weixin_30733003/article/details/95404897
注意,linux下 .aws 是隐藏文件,使用ls -a可查看包括隐藏文件在内的所有文件

2.引入依赖

<dependency>
   <groupId>com.amazonaws</groupId>
    <artifactId>aws-java-sdk</artifactId>
    <version>1.9.6</version>
</dependency>

3.上传类代码如下

需要准备的还有bucketName和Regions,均可在AWS控制台获取

/**
 * 图片处理
 * @author sxd
 * @date 2020/6/17 10:50
 */
@Controller
@RequestMapping("/picture")
public class PictureController {

    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    public static String bucketName = "beta-china-game";

    public static AmazonGlacierClient client;

    /**
     * AWS OSS 图片上传
     * */
    @PostMapping("/awsUpload")
    @ResponseBody
    public AjaxResult awsUpload(@RequestParam("filePic") MultipartFile filePic) {
        try
        {
            // 上传并返回新文件名称
            log.info("开始上传文件");

            File fileFile = multipartFileToFile(filePic);
            //获取文件名
            String remoteFileName = "game-pic-" + fileFile.getName();
            // 开始上传
            String pictureAwsUrl = upload(fileFile, remoteFileName);
            //上传成功
            if (pictureAwsUrl != null) {
                // AWS默认文件链接有效期为15分钟,为保证链接长期有效,只保留?前面的部分
                String pictureAwsUrlDeal = pictureAwsUrl.substring(0, pictureAwsUrl.indexOf("?"));
                AjaxResult ajax = AjaxResult.success();
                ajax.put("fileName", fileFile.getName());
                ajax.put("url", pictureAwsUrlDeal);
                return ajax;
            } else {
                return AjaxResult.error("上传失败!请稍后重试!");
            }
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    public String upload(File pic, String remoteFileName) throws IOException {
        try {
            AmazonS3 s3 = new AmazonS3Client();
            Region usWest2 = Region.getRegion(Regions.AP_NORTHEAST_1);
            s3.setRegion(usWest2);

            s3.putObject(new PutObjectRequest(bucketName, remoteFileName, pic)
                    .withCannedAcl(CannedAccessControlList.PublicRead));
            GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, remoteFileName);
            URL url = s3.generatePresignedUrl(urlRequest);
            return url.toString();
        } catch (AmazonServiceException ase) {
            ase.printStackTrace();
        } catch (AmazonClientException ace) {
            ace.printStackTrace();
        }
        return null;
    }

	/**
     * MultipartFile文件类型转化为File类型
     * */
    public static File multipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若需要防止生成的临时文件重复,可以在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章