【日常记录-Java】SpringBoot将文件上传到另外一个服务

发布于:2024-08-25 ⋅ 阅读:(122) ⋅ 点赞:(0)
Author:赵志乾
Date:2024-08-22
Declaration:All Right Reserved!!!

1. 引入依赖

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. application.yml增加配置

upload:
  url: http://localhost:8080/api/upload

3. 生成RestTemplate

@Configuration
public class BeanConfig {

    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

4. 上传服务

@Slf4j
@Service
public class FileUploadService implements IFileUploadService {

    @Resource
    private RestTemplate restTemplate;
    @Value("${upload.url}")
    private String uploadUrl;

    @Override
    public boolean uploadExcel(File file, String taskId, String sign) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        FileSystemResource resource = new FileSystemResource(file);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", resource);
        body.add("taskId", taskId);
        body.add("sign", sign);

        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(body, headers);
        ResponseEntity<Boolean> response = restTemplate.postForEntity(uploadUrl, request, Boolean.class);
        if (!response.getStatusCode().equals(HttpStatus.OK)) {
            return false;
        }
        return response.getBody();
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到