将一个字节流(可以是文本图片excel等文件) 上传到 文件服务器

1.

 /**
     * 功能描述: 文件服務器上传 excel 文件
     * @author guoyiguang
     * @date 2023/11/10
     * @param
     * @return
     */
    public  static  Object fileUpload(String fileName,byte[] bytes) {
        long start = System.currentTimeMillis();
        log.info("开始上传文件, 数量 {} 字节",bytes.length);
        Map param = new HashMap<>();//其他参数,自行添加

        HttpPost httppost = new HttpPost("http://aaa/bbb/网关/filsvr/File/Upload"); //fileUploadUrl 上传地址

        //根据需要设置头信息
        httppost.addHeader("token", "XXX");
        httppost.addHeader("tenant-id", "XXXX");

        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;
        String sResponse = null;
        try {
            httpClient = HttpClientBuilder.create().build();
            // HttpMultipartMode.RFC6532参数的设定是为避免文件名为中文时乱码
            MultipartEntityBuilder builder = MultipartEntityBuilder.create()
                    .setMode(HttpMultipartMode.RFC6532);
           // String s = JSONUtil.toJsonStr(list);
            //InputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
            builder.addBinaryBody("file",bytes, ContentType.DEFAULT_BINARY, fileName);
            // 添加参数
            if (param != null) {
                for (String key : param.keySet()) {
                    String value = param.get(key);
                    if (!StrUtils.isEmptyIfStr(value)) {
                        builder.addTextBody(key, value);
                    }
                }
            }
            HttpEntity reqEntity = builder.build();
            httppost.setEntity(reqEntity);

            response = httpClient.execute(httppost);
            HttpEntity responseEntity = response.getEntity();
            sResponse = EntityUtils.toString(responseEntity, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("调用上传文件出错:" + e.getMessage());
        }
        JSONObject jsonObject = JSONObject.parseObject(sResponse);

        long end = System.currentTimeMillis();
        log.info("上传文件结束,耗时{} 毫秒",end-start);

        return  jsonObject;
    }

你可能感兴趣的:(excel,服务器,运维)