private <T> InputStream getFileInputStream( List<T> list, String sheetName) {
if (list == null || list.isEmpty()) {
return null;
}
Class<?> clazz = list.get(0).getClass();
ByteArrayOutputStream out = new ByteArrayOutputStream();
ExcelUtil excelUtil = new ExcelUtil<>(clazz);
excelUtil.exportExcel(list, sheetName, out);
byte[] bytes = out.toByteArray();
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
return in;
}
public List<String> UploadFile() {
String host =192.168.120.1
String url = host + "/v2.0/upload/file";
HttpPost post = new HttpPost(url);
MultipartEntityBuilder EntityBuilder = MultipartEntityBuilder.create();
ContentType contentType = ContentType.create("text/plain", Charset.forName("UTF-8"));
try {
List<String> list=new ArrayList<>;
String sheetName ="测试excel";
InputStream in = this.getFileInputStream(list, sheetName);
EntityBuilder.addBinaryBody("file", in, ContentType.MULTIPART_FORM_DATA, sheetName + ".xls");
post.setEntity(EntityBuilder.build());
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, "UTF-8");
JSONObject jsonObject = JSONObject.fromObject(res);
JSONArray data = jsonObject.getJSONArray("data");
List<String> list = new ArrayList<>();
for (int i = 0; i < data.size(); i++) {
JSONObject jsonObject1 = data.getJSONObject(i);
String filename = jsonObject1.getString("filename");
list.add(filename);
}
return list;
} catch (Exception e) {
logger.error("上传excel到oss异常", e);
return null;
}
}