1、推送附件 filebody
/**
     *  推送附件方法
     *  @param args
     */
    public static void main2(String[] args){

        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();

            // 把一个普通参数和文件上传给下面这个地址 是一个servlet
            HttpPost httpPost = new HttpPost("http://localhost:8088/api/xfSystemToJsxf/acceptOutSystemUpload");
            // 请求头设置token值
            httpPost.setHeader("token", "8c17f4d7-c53a-42e3-aa22-8f3f8e41f25e");
            StringBody extendId = new StringBody("705d7630-d097-4a4c-806e-61b0cd50ba2f", ContentType.create(
                    "text/plain", "utf-8"));
            StringBody extendCaseCode = new StringBody("NJ12369", ContentType.create(
                    "text/plain", "utf-8"));
            // 相当于<input type="text" name="extendId" value=extendId>
            MultipartEntityBuilder meb = MultipartEntityBuilder.create()
            .addPart("extendId", extendId)
            .addPart("extendCaseCode", extendCaseCode);
            List<FileBody> fileBodyList=new ArrayList<>();
            fileBodyList.add(new FileBody(new File("C:\\Users\\wangmq\\Desktop\\附件1.docx")));
            fileBodyList.add(new FileBody(new File("C:\\Users\\wangmq\\Desktop\\附件2.doc")));
            for(int i=0; i<fileBodyList.size(); i++){
                FileBody fileBody=fileBodyList.get(i);
                // 把文件转换成流对象FileBody
                StringBody fileName = new StringBody(fileBody.getFilename(), ContentType.create(
                        "text/plain", "utf-8"));
                meb.addPart("fileName"+i, fileName);
                meb.addPart("fileBody"+i, fileBody);
            }
            // setMode(HttpMultipartMode.RFC6532)解决文件名中文成?的问题
            HttpEntity reqEntity = meb.setMode(HttpMultipartMode.RFC6532).build();
            httpPost.setEntity(reqEntity);

            // 发起请求 并返回请求的响应
            response = httpClient.execute(httpPost);

            System.out.println("响应状态码==========" + response.getStatusLine());
            System.out.println("响应头===========" + response.getLastHeader("fileResult"));

            // 获取响应对象
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                // 打印响应长度
                System.out.println("Response content length: " + resEntity.getContentLength());
                // 打印响应内容
                System.out.println(EntityUtils.toString(resEntity, Charset.forName("UTF-8")));
            }

            // 销毁
            EntityUtils.consume(resEntity);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(response != null){
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if(httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

2、接收推送的附件 filebody

@ResponseBody
    @RequestMapping(value = "/acceptJsxfManageFile", method = RequestMethod.POST)
    public JsonResult acceptJsxfManageFile(HttpServletRequest request, HttpServletResponse response){
        JsonResult jsonResult = JsonResult.getSuccessResult();
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            // 开始保存附件
            String jsxfManageFilePath = ConfigUtil.getConfigValueByKey("jsxfManageFilePath");
            File uploadFile = new File(jsxfManageFilePath);
            if (!uploadFile.exists()) {
                uploadFile.mkdirs();
            }
            // 检测是不是存在上传文件
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if(isMultipart){
                DiskFileItemFactory factory = new DiskFileItemFactory();
                //指定在内存中缓存数据大小,单位为byte,这里设为50Mb
                factory.setSizeThreshold(50*1024*1024);
                //设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
                factory.setRepository(new File("C:\\temp"));
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                // 指定单个上传文件的最大尺寸,单位:字节,这里设为50Mb
                upload.setFileSizeMax(50 * 1024 * 1024);
                //指定一次上传多个文件的总尺寸,单位:字节,这里设为99Mb
                upload.setSizeMax(99 * 1024 * 1024);
                upload.setHeaderEncoding("UTF-8");
                List<FileItem> items = null;
                // 解析request请求
                items = upload.parseRequest(request);
                // 外部系统案件主键id
                String extendId = "";
                if(items!=null){
                    //解析表单项目
                    Iterator<FileItem> iter = items.iterator();
                    // MultipartEntityBuilder对象的addPart设置参数是有序的,就按照设置的先后自然顺序排列
                    // 遍历变化的fileStatus
                    String fileStatusIter = "";
                    String fileNameIter = "";
                    int acceptFileNum = 0;
                    while (iter.hasNext()) {
                        FileItem item = iter.next();
                        //如果是普通表单属性
                        if (item.isFormField()) {
                            //相当于input的name属性   <input type="text" name="content">
                            String name = item.getFieldName();
                            //input的value属性
                            String value = item.getString();
                            if("extendId".equals(name)){
                                extendId = value;
                            }
                            // 设置遍历变化的fileStatus
                            if(name.indexOf("fileStatus")!=-1){
                                fileStatusIter = value;
                            }
                            // 设置遍历变化的filename
                            if(name.indexOf("fileName")!=-1){
                                fileNameIter = value;
                            }
                        } else {
                            // 是文件,加一层文件夹路径,文件夹名为外部系统案件主键id
                            String uploadPathExtendId = jsxfManageFilePath+"\\"+extendId+"\\";
                            File uploadPathExtendIdDir = new File(uploadPathExtendId);
                            if(!uploadPathExtendIdDir.exists()){
                                uploadPathExtendIdDir.mkdirs();
                            }
                            //属性名
                            String fieldName = item.getFieldName();
                            //上传文件路径
//                            String fileName = item.getName();
                            String fileName = fileNameIter;
                            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);// 获得上传文件的文件名
                            // 文件输出流写到本地硬盘保存
                            item.write(new File(uploadPathExtendIdDir, fileName));
                            acceptFileNum ++;
                            // 插入中间库案件和附件的关联信息
                            if(systemService.addLocaleSurvey(fileStatusIter, extendId, uploadPathExtendId, fileName, ComplainContant.JSXF_MANAGE_FILE)){
                                jsonResult.setTotal(acceptFileNum);
                            }
                        }
                    }
                }
            }
        }catch (Exception e){
            jsonResult.setSuccess(false);
            e.printStackTrace();
        }finally {
            return jsonResult;
        }
    }

3、j将自己文件打包,供别人获取

@ResponseBody
    @RequestMapping(value = "takeOutSystemUpload")
    public void takeOutSystemUpload(@RequestBody DataSyncParam dataSyncParam, HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        OutputStream out = response.getOutputStream();
        ZipOutputStream zos = new ZipOutputStream(out);
        // 外部系统案件主键id
        String extendId = dataSyncParam.getExtendId();
        try {
            if(StringUtils.isNullOrEmpty(extendId)){
                response.setStatus(4003);
                response.setHeader("fileResult", "error, extendId is null");
            }else{
                // 根据extendid找到文件夹,遍历获取要打包的多个文件
                String filePathNameDir = ConfigUtil.getConfigValueByKey("outSystemUploadPath")+extendId+"\\";
                File[] fileArray = new File(filePathNameDir).listFiles();
                if(fileArray == null){
                    response.setStatus(4004);
                    response.setHeader("fileResult","error, extendId is invalid");
                }else{
                    int takeFileNum = 0;
                    for(File file : fileArray){
                        ZipEntry entry = new ZipEntry(file.getName());
                        zos.putNextEntry(entry);
                        byte [] bytes = new byte[1024];
                        int len;
                        FileInputStream in = new FileInputStream(file);
                        while((len = in.read(bytes)) != -1) {
                            zos.write(bytes, 0, len);
                        }
                        takeFileNum++;
                        zos.closeEntry();
                        in.close();
                    }
                    response.setStatus(200);
                    response.setHeader("fileResult","success, return "+takeFileNum+" files successfully");
                }
            }
        } catch (Exception e) {
            response.setStatus(-1);
            e.printStackTrace();
        }finally {
            if(zos != null) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

4、获取打包的附件

public static void main4(String[] args){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        Map<String, String> params = new HashMap<>();
        String extendId = "705d7630-d097-4a4c-806e-61b0cd50ba2f";
        params.put("extendId", extendId);
        //发送http请求,并处理返回的zip包 
        HttpPost httpPost = new HttpPost("http://localhost:8088/api/xfSystemToJsxf/takeJsxfManageFile");
        httpPost.addHeader("token", "c279adad-0cb0-4d3c-9436-644d513c41fa");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(Charset.forName("utf-8"));
        String value = "";
        if (params != null) {
            for (String key : params.keySet()) {
                value = (String)params.get(key);
                if (value == null) value = "";
                builder.addTextBody(key, value, ContentType.APPLICATION_JSON);
            }
        }
        HttpEntity multipart = builder.setMode(HttpMultipartMode.RFC6532).build();
        httpPost.setEntity(multipart);
        Map<String, Object> map = new HashMap<>();
        try {
            httpClient = HttpClients.createDefault();
            response = httpClient.execute(httpPost);
            String[] statusLineArray = response.getStatusLine().toString().split(" ");
            System.out.println("响应状态吗===========" + response.getStatusLine());
            System.out.println("响应头===========" + response.getLastHeader("fileResult"));
            if("200".equals(statusLineArray[1])){
                try {
                    HttpEntity entity = response.getEntity();//从response里获取数据实体
                    InputStream in = entity.getContent();//获取数据流
                    Charset c = Charset.forName("UTF-8");
                    ZipInputStream zin = new ZipInputStream(in, c);//封装成zip输入流
                    BufferedOutputStream bos = null;
                    ZipEntry ze;
                    // // 加一层文件夹路径,文件夹名为外部系统案件主键id
                    String path = "C:\\Users\\wangmq\\Desktop\\outSystemManageFile\\"+extendId+"\\";
                    File filePathDir = new File(path);
                    if(!filePathDir.exists()){
                        filePathDir.mkdirs();
                    }
                    File file = null;
                    while((ze = zin.getNextEntry()) != null) {//循环zip输入流,获取每一个文件实体
                        file = new File(path + ze.getName());//生成file(如果文件路径不存在,先创建)
                        FileOutputStream fos = new FileOutputStream(file);
                        int len;
                        byte [] bytes = new byte[2048];
                        bos = new BufferedOutputStream(fos,2048);
                        while((len = zin.read(bytes, 0, 2048)) != -1) {
                            bos.write(bytes, 0, len);
                        }
                        bos.flush();
                        bos.close();
                    }
                    zin.close();//关闭输入流
                }catch(Exception e){
                    e.printStackTrace();
                } finally {
                    if (response != null) response.close();
                }
            }
        } catch (IOException e) {
            logger.error("获取附件发送异常" + e);
        }

    }
01-19 11:23