Spring Boot Sping Boot :文件上传到s3是在本地工作,而与ide的工作,但在构建后,它是显示错误文件未找到

fkvaft9z  于 2023-08-04  发布在  Spring
关注(0)|答案(1)|浏览(109)

我的awss3配置代码是

@Data
@Configuration
public class AWSConfig {

    @Value("${aws.s3.secretKey}")
    private String secretKey;
    @Value("${aws.s3.accessKey}")
    private String accessKey;
    @Value("${aws.s3.bucketName}")
    private String bucketName;
    @Value("${aws.s3.region}")
    private String region;

    @Bean
    public AmazonS3 s3Client() {
        AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        return AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(region).build();
    }

}

字符串
而文件上传服务文件是

@Service
@Slf4j
public class AWSUploadServiceImpl implements AWSUploadFileService {

    @Value("${aws.s3.bucketName}")
    private String bucketName;

    @Autowired
    private AmazonS3 s3Client;
    @Override
    public String uploadFile(File file, String path) {
        s3Client.putObject(new PutObjectRequest(bucketName, path, file));
        return "File uploaded" ;
    }

    @Override
    public byte[] downloadFile(String fileName) {
        S3Object s3Object = s3Client.getObject(bucketName, fileName);
        S3ObjectInputStream inputStream = s3Object.getObjectContent();
        try {
            byte[] content = IOUtils.toByteArray(inputStream);
            return content;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public String deleteFile(String fileName) {
        s3Client.deleteObject(bucketName, fileName);
        return fileName + " removed ...";
    }

}


和转换器,我用它来转换multipartfile文件是

private File convertMultipartToFile(MultipartFile multipartFile) {
        File file = new File(Objects.requireNonNull(multipartFile.getOriginalFilename()));
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(multipartFile.getBytes());
        } catch (Exception ignored) {}
        return file;
    }


我试图从API上传文件到s3,这是在 Spring 启动创建的,它是与ide工作,但在构建后,它不上传文件?

h5qlskok

h5qlskok1#

在构建Sping Boot 应用程序后将文件上传到S3所面临的问题可能与文件路径处理有关。从IDE运行应用程序时,工作目录通常设置为项目根目录,因此您提供的文件路径可能有效。但是,当您构建应用程序并将其作为JAR文件运行时,工作目录会发生更改,这可能会导致File not found错误。
也许你可以试试这个

private File convertMultipartToFile(MultipartFile multipartFile) {
    String tempDir = System.getProperty("java.io.tmpdir");
    File file = new File(tempDir + File.separator + multipartFile.getOriginalFilename()); // only example or you set Manuelly the path ... i dont know...
    try {
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(multipartFile.getBytes());
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return file;
}

字符串
重要:确保更新AWSUploadServiceImpl类中的uploadFile方法,以便也使用绝对文件路径。

相关问题