简体   繁体   中英

How get file data from post request in NETTY 4?

I can send this POST request with some jpg file to my server

POST /formpostmultipart HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 621551
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2031.2 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryY1m4URqQ5ydALOrQ
Referer: http://localhost:8080/upload
Accept-Encoding: gzip,deflate,sdch
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4

what must i do for get file from this request and save to disk for example? ps sorry for my bad english

i solve this problem with HttpPostRequestDecoder. for example

if (request.getMethod().equals(HttpMethod.POST)) {
                    decoder = new HttpPostRequestDecoder(dataFactory, request);
                    decoder.setDiscardThreshold(0);
if (decoder != null) {
        if (msg instanceof HttpContent) {
            HttpContent chunk = (HttpContent) msg;
            decoder.offer(chunk);
            readChunk(channelHandlerContext);
            if (chunk instanceof LastHttpContent) {
                resetPostRequestDecoder();
            }
        }
    }
private void readChunk(ChannelHandlerContext ctx) throws IOException {
    while (decoder.hasNext()) {
        InterfaceHttpData data = decoder.next();
        if (data != null) {
            try {
                switch (data.getHttpDataType()) {
                    case Attribute:
                        break;
                    case FileUpload:    
                        FileUpload fileUpload = (FileUpload) data;
                        File file = new File("C:\\test\\" + fileUpload.getName);
                        if (!file.exists()) {
                            file.createNewFile();
                        }
                        try (FileChannel inputChannel = new FileInputStream(fileUpload.getFile()).getChannel(); FileChannel outputChannel = new FileOutputStream(file).getChannel()) {
                            outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
                            sendSimpleResponse(ctx,CREATED,"file name: " +file.getAbsolutePath());
                        }
                        break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                data.release();
            }
        }
    }
}

private void resetPostRequestDecoder() {
    request = null;
    decoder.destroy();
    decoder = null;
}

Here is an example using Netty 4.1.3.Final . Some snippets are taken from mechanikos' answer.

Pipeline is as follows:

pipeline.addLast(new HttpRequestDecoder());
pipeline.addLast(new HttpResponseEncoder());
pipeline.addLast(new MyHttUploadServerHandler());

Channel read handling:

protected void channelRead0(final ChannelHandlerContext ctx, final HttpObject httpObject)
    throws Exception {
    if (httpObject instanceof HttpRequest) {
      httpRequest = (HttpRequest) httpObject;
      final URI uri = new URI(httpRequest.uri());

      System.out.println("Got URI " + uri);
      if (httpRequest.method() == POST) {
        httpDecoder = new HttpPostRequestDecoder(factory, httpRequest);
        httpDecoder.setDiscardThreshold(0);
      } else {
        sendResponse(ctx, METHOD_NOT_ALLOWED, null);
      }
    }
    if (httpDecoder != null) {
      if (httpObject instanceof HttpContent) {
        final HttpContent chunk = (HttpContent) httpObject;
        httpDecoder.offer(chunk);
        readChunk(ctx);

        if (chunk instanceof LastHttpContent) {
          resetPostRequestDecoder();
        }
      }
    }
  }

  private void readChunk(ChannelHandlerContext ctx) throws IOException {
    while (httpDecoder.hasNext()) {
      InterfaceHttpData data = httpDecoder.next();
      if (data != null) {
        try {
          switch (data.getHttpDataType()) {
            case Attribute:
              break;
            case FileUpload:
              final FileUpload fileUpload = (FileUpload) data;
              final File file = new File(FILE_UPLOAD_LOCN + fileUpload.getFilename());
              if (!file.exists()) {
                file.createNewFile();
              }
              System.out.println("Created file " + file);
              try (FileChannel inputChannel = new FileInputStream(fileUpload.getFile()).getChannel();
                   FileChannel outputChannel = new FileOutputStream(file).getChannel()) {
                outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
                sendResponse(ctx, CREATED, "file name: " + file.getAbsolutePath());
              }
              break;
          }
        } finally {
          data.release();
        }
      }
    }
}

Full gist can be found here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM