Spring Boot使用RestTemplate转发文件

在Spring Boot中,使用RestTemplate发送文件通常涉及构建一个多部分(multipart)请求。以下是一个使用RestTemplate将接受到的文件转发给其它服务的示例:

Java

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;

public class FileUploader {

    private final RestTemplate restTemplate;

    public FileUploader(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
	
	/**
	**file为接受到的文件
	**/
    public ResponseEntity<String> uploadFile(String remoteUrl, MultipartFile file) throws Exception{
   		String fileName = file.getOriginalFilename();
   		//MultipartFile 转换为 File
        File fileToUpload= new File(FileUtils.getTempDirectoryPath() + File.separator+ fileName);
        FileUtils.copyInputStreamToFile(file.getInputStream(), fileToUpload);
        // 创建HTTP头部,设置为多部分表单类型
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 创建多值映射以存储表单数据
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        
        // 将要上传的文件包装成一个Resource对象
        FileSystemResource resource = new FileSystemResource(fileToUpload);
        
        // 添加文件到body中,key通常是目标服务接收文件的字段名
        body.add("file", resource );

        // 如果有其他表单字段,可以这样添加
        // body.add("otherField", "fieldValue");

        // 创建包含body和headers的HttpEntity
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 使用RestTemplate发送POST请求
        ResponseEntity<String> response = restTemplate.postForEntity(remoteUrl, requestEntity, String.class);

		//删除临时文件
		fileToUpload.delete();
        return response;
    }
}

在上面例子中,我们首先创建了一个HttpHeaders对象,并设置了Content-Type为multipart/form-data。然后,我们创建了一个LinkedMultiValueMap来存储表单数据,将要上传的文件作为FileSystemResource添加到map中。最后,我们将这个map封装进HttpEntity并用RestTemplate发送POST请求。

请注意,你需要根据目标服务的API文档调整请求URL、表单字段名以及请求头的内容。同时,确保已正确处理文件路径和文件存在性检查。另外,从Spring 5开始推荐使用WebClient替代RestTemplate进行HTTP通信,因为它提供了更强大的异步和响应式功能。

  • 14
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,为了实现文件上传功能,需要几步操作: 1. 在 `pom.xml` 中添加文件上传所需的依赖,如 `commons-fileupload` 和 `commons-io` 2. 在 `application.properties` 中配置文件上传的相关参数,如文件上传路径 3. 在Controller 中添加上传文件的接口 4. 在service层添加上传文件的实现逻辑 具体实现过程如下: 1. 在 `pom.xml` 中添加文件上传所需的依赖,如下: ```xml <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.8.0</version> </dependency> ``` 2. 在 `application.properties` 中配置文件上传的相关参数,如文件上传路径,如下: ``` file.upload-dir=D:\\file\\ ``` 3. 在Controller 中添加上传文件的接口,如下: ```java @Controller @RequestMapping("/file") public class FileUploadController { @Autowired private FileUploadService fileUploadService; @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { fileUploadService.uploadFile(file); redirectAttributes.addFlashAttribute("message", "You successfully uploaded " + file.getOriginalFilename() + "!"); return "redirect:/file/uploadStatus"; } @GetMapping("/uploadStatus") public String uploadStatus() { return "uploadStatus"; } } ``` 4. 在service层添加上传文件的实现逻辑,如下: ```java @Service public class FileUploadServiceImpl implements FileUploadService { @Value("${file.upload-dir}") private String UPLOAD_DIR;

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值