栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用RestTemplate Spring-mvc发送Multipart表单数据

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用RestTemplate Spring-mvc发送Multipart表单数据

ByteArrayResource
大文件读取整个文件可能是内存消耗问题。

您可以使用以下命令在spring mvc控制器中代理文件上传

InputStreamResource

@RequestMapping(value = "/upload", method = RequestMethod.POST)public ResponseEntity<?> uploadImages(@RequestPart("images") final MultipartFile[] files) throws IOException {    linkedMultiValueMap<String, Object> map = new linkedMultiValueMap<>();    String response;    HttpStatus httpStatus = HttpStatus.CREATED;    try {        for (MultipartFile file : files) { if (!file.isEmpty()) {     map.add("images", new MultipartInputStreamFileResource(file.getInputStream(), file.getOriginalFilename())); }        }        HttpHeaders headers = new HttpHeaders();        headers.setContentType(MediaType.MULTIPART_FORM_DATA);        String url = "http://example.com/upload";        HttpEntity<linkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>(map, headers);        response = restTemplate.postForObject(url, requestEntity, String.class);    } catch (HttpStatusCodeException e) {        httpStatus = HttpStatus.valueOf(e.getStatusCode().value());        response = e.getResponseBodyAsString();    } catch (Exception e) {        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;        response = e.getMessage();    }    return new ResponseEntity<>(response, httpStatus);}class MultipartInputStreamFileResource extends InputStreamResource {    private final String filename;    MultipartInputStreamFileResource(InputStream inputStream, String filename) {        super(inputStream);        this.filename = filename;    }    @Override    public String getFilename() {        return this.filename;    }    @Override    public long contentLength() throws IOException {        return -1; // we do not want to generally read the whole stream into memory ...    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/451410.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号