POST multipart/form-data 上传多个文件

POST multipart/form-data 上传多个文件
httpmime-4.3.6

CloseableHttpClient httpClient = HttpClients.createDefault();  
                URIBuilder uri = new URIBuilder();
                uri.setScheme("http").setHost("127.0.0.1").setPort(8000).setPath("/_upload");

                uri.setParameter("containOriFile", textMap.get("containOriFile"));
                uri.setParameter("ticket", tickets);
                JSONObject json = JSONObject.fromObject(sample);//将java对象转换为json对象
                String str = json.toString();//将json对象转换为字符串
                byte[] bytes=str.getBytes("UTF-8");
                try {
                    Logger.info("1****************"+uri);
                    HttpPost post=new HttpPost(uri.build());
                    MultipartEntityBuilder entityBuilder=MultipartEntityBuilder.create();
                    ContentBody contentBody=new ByteArrayBody(bytes, ContentType.APPLICATION_OCTET_STREAM, fileName);
                    entityBuilder.addPart("metaFile", contentBody);
                    for (int i = 1; i < file_list.size(); i++) {
                        File file=new File(imagePaths+file_list.get(i).name);
                        FileBody fileBody=new FileBody(file,  ContentType.APPLICATION_OCTET_STREAM, file.getName());
                        entityBuilder.addPart("oriFile", fileBody);
                    }
                    HttpEntity entity=entityBuilder.build();
                    post.setEntity(entity);
                    Logger.info("2****************"+post);
                    CloseableHttpResponse response =httpClient.execute(post);
                    Logger.info("3****************"+response.getStatusLine().getStatusCode());
                    if(response.getStatusLine().getStatusCode()==200){  
                        System.out.println(EntityUtils.toString(response.getEntity()));  
                        //以下这种方式读取流也可以,只不过用EntityUtils会更方便  
                        /*InputStream is = response.getEntity().getContent(); 
                        ByteArrayOutputStream os = new ByteArrayOutputStream(); 
                        byte[] buffer = new byte[1024]; 
                        int len=-1; 
                        while((len = is.read(buffer))!=-1){ 
                            os.write(buffer,0,len); 
                        } 
                        os.close(); 
                        is.close(); 
                        System.out.println(os.size()+new String(os.toByteArray(),"utf-8"));*/  
                    }  
                } catch (URISyntaxException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章