前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用RestTemplate上传文件

使用RestTemplate上传文件

作者头像
CBeann
发布2023-12-25 19:08:43
3570
发布2023-12-25 19:08:43
举报
文章被收录于专栏:CBeann的博客CBeann的博客

写作目的

最近维护一个项目,里面用了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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-03-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 写作目的
  • 代码
  • 参考
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档