java - 使用 Spring 的 RestTemplate 将文件作为 block 发送

标签 java file file-upload inputstream

我要调用 POST REST API,该 API 接受其主体中的文件。

如果我发送几 KB 的文件(使用下面的代码),大约需要 300 毫秒。而且,如果我发送大约 5 GB 的文件,它会抛出内存不足异常。

是否有可能将文件作为 block 按顺序发送?目前,我们正在避免任何并行处理。

非常感谢代码或引用中的任何帮助。

public static Resource getTestFile() throws IOException {
    Path testFile = Paths.get(FILE_PATH);
    System.out.println("Creating and Uploading Test File: " + testFile);
    return new FileSystemResource(testFile.toFile());
}
private static void uploadSingleFile() throws IOException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

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

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

    String serverUrl = "http://localhost:8080/place";

    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<DataTransportResponse> response = restTemplate.postForEntity(serverUrl, requestEntity,
                    DataTransportResponse.class);

    System.out.println("Response code: " + response.getStatusCode());
}

spring:
  application:
    name: file-manager
  servlet:
    multipart:
      max-file-size: 20480MB
      max-request-size: 2048MB 
application:
  seal:
    id: 104912

最佳答案

你可以试试这个方法

@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
    multipartResolver.setMaxUploadSize(54525952); //...specify your size of file  (20971520 - 20 MB) (54525952 - 52 MB)
    return multipartResolver;
}

我从这个链接post找到了这个引用资料。希望对您有所帮助。

关于java - 使用 Spring 的 RestTemplate 将文件作为 block 发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60422807/

相关文章:

ruby - 目录内容是否已更改?

php - move_uploaded_file 无法打开流 : Permission denied - Mac

带有 https 和凭据的 android fileupload

amazon-web-services - 使用 AWS EC2 实例提高上传速度

java - 如何知道日期是否在前 x 分钟内?

java - 计算每个唯一字符的出现次数

java - Eclipse 插件从当前打开的文件中获取代码

java - 如何将连字符分隔的标签名称转换为驼峰大小写

java - Java 中的值匹配和降维

c++ - 文件映射打开 (Windows)