我可以将此POST请求和一些jpg文件发送到我的服务器
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
我必须怎么做才能从此请求中获取文件并保存到磁盘?ps对不起我的英语不好
我用HttpPostRequestDecoder解决了这个问题。例如
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句