使用RestTemplate上传文件

2023-12-25 19:08:43 浏览数 (1)

写作目的

最近维护一个项目,里面用了RestTemplate进行服务之前的调用,不过最近有一个Excel解析的需求,百度了几篇,内容不是很全,所以写篇博客记录一下,不过我还是推荐使用Feign调用,毕竟面向接口编程,方便。

代码

亲测可用

代码语言:javascript复制
@RestController
public class DataExcelImportController {


    private static final String REST_URL_PRFIX = "http://abc";

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/importExcel")
    public Object explainExcel(Integer stationId, @RequestPart("file") MultipartFile file) throws Exception {

        if (file.isEmpty()) {
            return "文件为空";
        }

        FdcpResult result = null;
        File file1 = null;
        try {
            //转换为file
            file1 = multipartFileToFile(file);

            FileSystemResource resource = new FileSystemResource(file1);
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            //参数
            param.add("file", resource);
            param.add("stationId", stationId);

            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(param);
            ResponseEntity<FdcpResult> responseEntity = restTemplate.exchange(REST_URL_PRFIX   "/importExcel", HttpMethod.POST, httpEntity, FdcpResult.class);


            result = responseEntity.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != file) {
                //最后要删除
                file1.delete();
            }
        }
        return result;

    }

    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

参考

使用RestTemplate上传文件 - 简书

MultipartFile转File_唐僧洗发用飘柔-CSDN博客_multipartfile转file

0 人点赞