如何利用JAVA获取文件流并转换为文件格式存储

本文介绍了如何使用Java的CloseableHttpClient库通过HTTP请求从指定URL下载文件,处理文件名和类型,然后将文件添加到MultipartFile列表中,处理可能的IOExceptions。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

String[] split = fileKeys.split(",");
CloseableHttpClient client = HttpClients.createDefault();
List<MultipartFile> fileList = new ArrayList<>();
通过附件id循环获取文件
  for (String fileKey : split) {
       //判断是否为空
        if (StringUtils.isNotBlank(fileKey)){
            //请求路径
            String fileUrl = "http://localhoost:8080/ltcFile/download/"+fileKey;
            CloseableHttpResponse fileResponse = null;
            HttpGet httpGet = new HttpGet(fileUrl);
            // 获取header中文件类型
            String fileName = "";int x=0;
               try {
                    fileResponse = client.execute(httpGet);
                    if (fileResponse.getStatusLine().getStatusCode() == 200) {
                        Header[] headers = fileResponse.getAllHeaders();
                        String value = headers[x].getValue();
                        System.out.println(value);
                        fileName=value;

                        HttpEntity fileEntity = fileResponse.getEntity();
                        InputStream inputStream = fileEntity.getContent();
                        MultipartFile multipartFile = new MockMultipartFile
                                (URLDecoder.decode(fileName, "UTF-8"),URLDecoder.decode(fileName, "UTF-8"),
                                        ContentType.APPLICATION_OCTET_STREAM.toString(),inputStream);
                        fileList.add(multipartFile);
                        logger.info(multipartFile.getOriginalFilename());

                        inputStream.close();
                    }
                } catch (IOException e) {
                    logger.error(e.getMessage());
                }finally {
                    try {
                        fileResponse.close();
                    } catch (IOException e) {
                        logger.error(e.getMessage());
                    }
                }
            }
        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值