首页 > 解决方案 > 在 Spring Boot 中将文件上传到 S3 并将它们存储在类路径中

问题描述

我有方法将文件从用户上传到 S3 存储桶。但是当我测试它时,它既保存在 S3 buckend 上,也保存在我的类路径中。这是我上传文件的功能:

    public void uploadFileToNews(byte[] file, String fileName) {
    File fileToSave = new File(fileName);
    try(FileOutputStream fileOutputStream = new FileOutputStream(fileToSave) ) {
        fileOutputStream.write(file);
        amazonS3.putObject(new PutObjectRequest("gwnews", fileName, fileToSave));
    } catch (IOException e) {
        log.error("Error during uploading file to S3", e);
    }
}

这是我的服务中的功能:

    public News addNewsImage(MultipartFile multipartFile, String newsId) throws IOException {
    News news = getById(newsId);
    news.setImageUrl(news.getId() + ".png");
    fileService.uploadFileToNews(multipartFile.getBytes(), news.getId() + ".png");
    return newsRepository.save(news);
}

难道我做错了什么?如何避免将文件保存到我的类路径?

标签: javaspringamazon-s3

解决方案


此行将内容保存在您的类路径中:“fileOutputStream.write(file);” 下一行是将其保存在相应 AWS 账户的 S3 存储桶中。


推荐阅读