使用HttpClient发送InputStream--buffer对象,程序如下:
public String fileUpload(byte[] buffer, String url, int count, String classId) throws IOException {
//创建HttpClient对象
CloseableHttpClient client = HttpClients.createDefault();
//构建POST请求 请求地址请更换为自己的。
//1)
HttpPost post = new HttpPost(url);
InputStream inputStream = new ByteArrayInputStream(buffer);
try {
//文件路径请换成自己的
//2)
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
//第一个参数为 相当于 Form表单提交的file框的name值 第二个参数就是我们要发送的InputStream对象了
//第三个参数是文件名
//3)
builder.addBinaryBody("fileName", inputStream, ContentType.create("multipart/form-data"), count + "_" + classId + ".jpg");
//4)构建请求参数 普通表单项
/*StringBody stringBody = new StringBody("12", ContentType.MULTIPART_FORM_DATA);
builder.addPart("id",stringBody);*/
HttpEntity entity = builder.build();
post.setEntity(entity);
//发送请求
HttpResponse response = client.execute(post);
entity = response.getEntity();
if (entity != null) {
inputStream = entity.getContent();
//转换为字节输入流
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, Consts.UTF_8));
String body = null;
while ((body = br.readLine()) != null) {
logger.info("body=" + body);
return body;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}