首页 > 解决方案 > 找不到类 java.io.File 的主要或单个公共构造函数

问题描述

我正在尝试将文件传递给我的 springboot 后端。(然后将上传到 s3 存储桶),但我收到了这个我无法弄清楚的错误。

文件本身将包含一个数组,一个字符串数组

错误 -

java.lang.IllegalStateException: No primary or single public constructor found for class java.io.File - and no default constructor found either

数据源 -

// Data saved to S3 bucket / downloadableData function
if (this.lng !== "0.000000" && this.lng !== "") {
   this.locationData.push([`Longitude: ${this.lng}, Latitude: ${this.lat}, Uncertainty Radius: ${this.uncertainty_radius} meters, Address: ${this.place_name}, Source: TEXT`])
   this.locationData = JSON.parse(JSON.stringify(this.locationData))
}

Axios 邮政 -

downloadableData() {
  const blob = new Blob([this.locationData],  {type: 'application/json'});
  const data = new FormData();
  data.append("document", blob);
  axios.post("http://localhost:8080/api/v1/targetLocation/uploadStreamToS3Bucket", blob)
},

Springboot方法——

public void uploadStreamToS3Bucket(File locations) {
    try {
        AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
                .withRegion(String.valueOf(awsRegion))
                .build();

        String bucketName = "downloadable-cases";
        String fileName = connectionRequestRepository.findStream() +".json";
        s3Client.putObject(new PutObjectRequest(bucketName, fileName, locations));
    } catch (AmazonServiceException ex) {
        System.out.println("Error: " + ex.getMessage());
    }
}

数据示例

标签: javaamazon-web-servicesspring-bootamazon-s3axios

解决方案


我看到你想上传一个包含 JSON 数据的文件。这可以通过这样的逻辑在 Spring BOOT 应用程序中完成。

<p>Upload images to an S3 Bucket. Each image will be analyzed!</p>

<form method="POST" onsubmit="myFunction()" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="Submit" />
</form>

要在 Spring Controller 中处理此上传,您可以使用以下逻辑:

    // Upload a file to place into an Amazon S3 bucket.
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ModelAndView singleFileUpload(@RequestParam("file") MultipartFile file) {

        try {

            byte[] bytes = file.getBytes();
            String name =  file.getOriginalFilename() ;

            // Put the file into the bucket.
            s3Client.putObject(bytes, bucketName, name);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ModelAndView(new RedirectView("photo"));
    }

现在你有了字节数组和文件名。您可以使用 AWS SDK for Java V2 将其放入 Amazon S3 存储桶中。

     private S3Client getClient() {
    Region region = Region.US_WEST_2;
    S3Client s3 = S3Client.builder()
            .credentialsProvider(EnvironmentVariableCredentialsProvider.create())
            .region(region)
            .build();

     return s3;
     } 

    // Places an image into a S3 bucket.
    public String putObject(byte[] data, String bucketName, String objectKey) {

      s3 = getClient();

      try {
        PutObjectResponse response = s3.putObject(PutObjectRequest.builder()
                        .bucket(bucketName)
                        .key(objectKey)
                        .build(),
                RequestBody.fromBytes(data));

        return response.eTag();

    } catch (S3Exception e) {
        System.err.println(e.getMessage());
        System.exit(1);
    }
    return "";
}

这是显示此用例的完整文档。此用例实际上使用 Amazon Rekognition 服务来分析 Amazon S3 存储桶中的照片;但是,它仍然演示了如何将文件从您的桌面成功上传到 Amazon S3 存储桶。此外,它是使用 AWS SDK For Java V2 实现的,这是 Amazon 推荐的版本。

使用适用于 Java 的 AWS 开发工具包创建用于分析照片的动态 Web 应用程序


推荐阅读