首页 > 解决方案 > java.io.FileNotFoundException 通过使用 Spring RestTemplate 上传具有文件名的文件

问题描述

我正在上传一个带有文件名的文件,下面是我的代码;

我的代码如下;

String filePath = "/C:/../../promoCode/" + fileName + ".txt";

    File targetFile = new File(filePath);

    FileWriter writer = new FileWriter(targetFile);
    BufferedWriter buffer = new BufferedWriter(writer);
    buffer.write(generatedVoucherText);

    String bucketName = "promocodes";

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    MultiValueMap<String, String> fileMap = new LinkedMultiValueMap<>();
    ContentDisposition contentDisposition = ContentDisposition
            .builder("form-data")
            .name("file")
            .filename(fileName)
            .build();
    fileMap.add(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString());

    FileReader reader = new FileReader(targetFile);
    BufferedReader bufferedReader = new BufferedReader(reader);

   String someByteArray = bufferedReader.readLine();

    HttpEntity<byte[]> requestEntity = new HttpEntity<>(someByteArray.getBytes(StandardCharsets.UTF_8), fileMap);


    MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
    body.add("file", requestEntity);

    HttpEntity<MultiValueMap<String, Object>> httpEntity =
            new HttpEntity<>(body, headers);

    minioService.postMinio2(httpEntity, bucketName);
    buffer.close();

我不知道为什么我有 I/O 异常。

FullStackTrace 发生异常日志详细信息:“http://sth-sth.apps.mbt.sth.local promocodes”的 POST 请求出现 I/O 错误:类路径资源 [C:/../../promoCode/ABF. txt] 无法解析为 URL,因为它不存在;嵌套异常是 java.io.FileNotFoundException:类路径资源 [C:/../../promoCode/ABF.txt] 无法解析为 URL,因为它不存在,类:类 org.springframework.web.client。资源访问异常

谢谢

标签: javaspringspring-bootvalidationjava-8

解决方案


推荐阅读