undertow文件上传

undertow文件上传配置需借助EagerFormParsingHandler,该处理器与其他Handler工作方式一样。

undertow通过一系列的Handler处理数据,工作方式与filter相似,每一个Handler负责处理一部分数据,然后调用下一个Handler。

Builder builder = Undertow.builder();
builder.addHttpListener(port, host);
RoutingHandler routes = new RoutingHandler();
builder.setHandler(routes);

文件上传配置

UploadFile.java

public class UploadHandler implements HttpHandler {

 private final HttpHandler next;

 public UploadHandler(HttpHandler next) {
  this.next = next;
 }

 @Override
 public void handleRequest(HttpServerExchange exchange) throws Exception {
  String relativePath = exchange.getRelativePath();
  if (relativePath.endsWith("upload/img")) {
   final FormDataParser parser = FormParserFactory.builder().build().createParser(exchange);
   try {
    FormData data = parser.parseBlocking();
    FormValue file = data.getFirst("file");
    String fileName = file.getFileName();
    if (file.isFile()) {
     Path path = file.getPath();
     if (path != null) {
     //此时文件已经存在undertow临时目录中,只需通过path对文件执行操作。
      next.handleRequest(exchange);
     }
    }
   } catch (Throwable e) {
    e.printStackTrace();
    exchange.setStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);
    exchange.endExchange();
   } finally {
    IoUtils.safeClose(parser);
   }
  } else {
   next.handleRequest(exchange);
  }
 }

}

配置Handler:

Builder builder = Undertow.builder();
builder.addHttpListener(port, host);
RoutingHandler routes = new RoutingHandler();
EagerFormParsingHandler form = new EagerFormParsingHandler();
form.setNext(new UploadHandler(routes));
builder.setHandler(form);