通过vertx-web上传文件

时间:2021-09-28 18:02:56
public void batchCreateProduct(RoutingContext context){
JSONObject resJson = new JSONObject();
List<String> keys = TrustFastReleaseKeyGenerate.getInstance().getTradeAssetsKeyList();
if(context.fileUploads()==null||context.fileUploads().isEmpty()){
resJson.put(Constant.RETURN_CODE, Constant.FAILED_FILE_UPLOAD_ERROR);
resJson.put(Constant.RETURN_MSG, "请上传文件");
LOG.info("上传文件失败,请上传文件");
context.response().end(resJson.toJSONString());
return;
}
FileUpload file = (FileUpload) context.fileUploads().toArray()[0];
JsonArray queryJsonArray = new JsonArray();
try{
OPCPackage opcPackage = OPCPackage.open(file.uploadedFileName());
XSSFWorkbook workbook = new XSSFWorkbook(opcPackage);
XSSFSheet sheet0 = workbook.getSheetAt(0);
for(int i = 1;i<sheet0.getLastRowNum();i++){
JsonObject item = new JsonObject();
for(int j=0;j<keys.size();j++){
XSSFCell cell = sheet0.getRow(i).getCell(j);
if(cell!=null){
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING:
item.put(keys.get(j),cell.getStringCellValue());
LOG.info(keys.get(j)+"--->"+"XSSFCell.CELL_TYPE_STRING:"+cell.getStringCellValue());
break;
case XSSFCell.CELL_TYPE_NUMERIC:
if(DateUtil.isCellDateFormatted(cell)){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue()));
item.put(keys.get(j),date);
LOG.info(keys.get(j)+"--->"+"Date Format:"+date);
}else{
DecimalFormat df = new DecimalFormat("############.####");
item.put(keys.get(j),df.format(cell.getNumericCellValue()));
LOG.info(keys.get(j)+"--->"+"XSSFCell.CELL_TYPE_NUMERIC:"+ Double.toString(cell.getNumericCellValue()));
}
break;
case XSSFCell.CELL_TYPE_BLANK:
break;
default:
resJson.put(Constant.RETURN_CODE, Constant.FAILED_FILE_UPLOAD_ERROR);
resJson.put(Constant.RETURN_MSG, "解析文件失败");
LOG.info("解析文件失败");
context.response().end(resJson.toString());
return;
}
}
}
if(!item.isEmpty()){
//这边可能还需要添加要素
item.put("productType", "6");
item = getQueryJSON(formatCreateProductJsonInfo(item, context));
queryJsonArray.add(item);
}
}
LOG.info("解析出来的数据:"+queryJsonArray.toString());
JsonObject queryJson = new JsonObject();
queryJson.put("products", queryJsonArray);
HttpClient http = client.getHttpClient(context.vertx());
http.post("/product/creatProduct", new Handler<HttpClientResponse>() {
@Override
public void handle(HttpClientResponse res) {
res.bodyHandler(new Handler<Buffer>() {
@Override
public void handle(Buffer productDetail) {
LOG.info("Backend :after creat productDetail----------" + productDetail.toString());
context.response().putHeader("Content-type", Constant.CONTENT_TYPE).end(productDetail.toString());
http.close();
}
});
}
}).end(Json.encode(queryJson));
}catch(Exception e){
resJson.put(Constant.RETURN_CODE, Constant.FAILED_FILE_UPLOAD_ERROR);
resJson.put(Constant.RETURN_MSG, "解析文件异常");
LOG.info("解析文异常");
LOG.info("INFO:"+e.getMessage());
context.response().end(resJson.toJSONString());
}
return;
}