http实现form表单带CSV或者Excele附件上传,数据不落盘实现方式

以往的印象里面,实现附件上传需要有附件在磁盘里面存在(可能是见识浅薄),想着怎么去优化一下,避免落盘,就引入了这种方式,实现很容易,只是没有实践过,实践导致认知限制

  <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5</version>
        </dependency>

public static void main(String[] args) {
  
        String url = "http://IP:port/api/wechat/email";
        Map<String, String> map = new HashMap<>();
        map.put("mail", "101@qq.com");
        map.put("content", "请关注附件内容");
        map.put("isHtml", "true");
        map.put("title", "bian.yanmingtest");
        uploadFileExcel(url, map);

    }


/**
     * 直接将list数据当做文件不落盘附件上传功能,发送邮件的
     * @param url
     * @param params
     * @return
     */
    public static String uploadFileExcel(String url, Map<String, String> params) {

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            if (params != null) {
                for (String key : params.keySet()) {
                    builder.addPart(key,
                            new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
                }
            }
            List<List<String>> head = head();
            List<List<Object>> lists = dataList();
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            EasyExcel.write(bos).sheet("sheet1").head(head).doWrite(lists);
            byte[] array = bos.toByteArray();
            builder.addPart("mfile",new ByteArrayBody(array,"test.xlsx"));

            HttpEntity reqEntity = builder.build();
            httpPost.setEntity(reqEntity);

            // 发起请求 并返回请求的响应
            response = client.execute(httpPost, HttpClientContext.create());
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(resultString);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    private static List<List<String>> head() {
        List<List<String>> list = com.alibaba.excel.util.ListUtils.newArrayList();
        List<String> head0 = com.alibaba.excel.util.ListUtils.newArrayList();
        head0.add("字符串" + System.currentTimeMillis());
        List<String> head1 = com.alibaba.excel.util.ListUtils.newArrayList();
        head1.add("数字" + System.currentTimeMillis());
        List<String> head2 = com.alibaba.excel.util.ListUtils.newArrayList();
        head2.add("日期" + System.currentTimeMillis());
        list.add(head0);
        list.add(head1);
        list.add(head2);
        return list;
    }

    private static List<List<Object>> dataList() {
        List<List<Object>> list = com.alibaba.excel.util.ListUtils.newArrayList();
        for (int i = 0; i < 10; i++) {
            List<Object> data = com.alibaba.excel.util.ListUtils.newArrayList();
            data.add("字符串" + i);
            data.add(0.56);
            data.add(new Date());
            list.add(data);
        }
        return list;
    }

public static String uploadFileExcel(String url, Map<String, String> params) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            if (params != null) {
                for (String key : params.keySet()) {
                    builder.addPart(key,
                            new StringBody(params.get(key), ContentType.create("text/plain", Consts.UTF_8)));
                }
            }
        
            String fileStr = "姓名,性别 \nbym,0\n test,1";
            byte[] fileBytes = fileStr.getBytes();
//            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileBytes);
            builder.addPart("mfile",new ByteArrayBody(fileBytes,"test.csv"));
//            builder.addPart("mfile", new InputStreamBody(byteArrayInputStream, "test.csv"));

            HttpEntity reqEntity = builder.build();
            httpPost.setEntity(reqEntity);

       
            response = client.execute(httpPost, HttpClientContext.create());
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(resultString);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

http这块的经验总结
https://www.cnblogs.com/bingyimeiling/p/11820583.html

posted @ 2024-08-21 11:28  堕落先锋  阅读(7)  评论(0编辑  收藏  举报