我需要有关servlet的帮助。
我需要在一个请求中读取一个inputStream并写一个tiff文件。 inputStream带有请求头,我不知道如何删除该字节并只写文件。
查看来自写文件的初始字节。
-qF3PFkB8oQ-OnPe9HVzkqFtLeOnz7S5Be
Content-Disposition: form-data; name=""; filename=""
Content-Type: application/octet-stream; charset=ISO-8859-1
Content-Transfer-Encoding: binary
我想删除它并只从tiff文件中写入字节。 PS:文件的发件人不是我。
答案 0 :(得分:1)
我不确定为什么你没有使用HttpServletRequest的getInputStream()方法来获取没有标题的内容,无论你是否有选择开始读取输入流并忽略内容,直到找到两个连续的CRLF,它定义了标题的结尾。
这样做的一种方式是:
String headers = new java.util.Scanner(inputStream).next("\\r\\n\\r\\n");
// Read rset of input stream
答案 1 :(得分:1)
Apache公共解决了90%的问题...只需要知道搜索中使用了哪些关键字:) “解析多部分请求” 和谷歌说: http://www.oreillynet.com/onjava/blog/2006/06/parsing_formdata_multiparts.html
int boundaryIndex = contentType.indexOf("boundary=");
byte[] boundary = (contentType.substring(boundaryIndex + 9)).getBytes();
ByteArrayInputStream input = new ByteArrayInputStream(buffer.getBytes());
MultipartStream multipartStream = new MultipartStream(input, boundary);
boolean nextPart = multipartStream.skipPreamble();
while(nextPart) {
String headers = multipartStream.readHeaders();
System.out.println("Headers: " + headers);
ByteArrayOutputStream data = new ByteArrayOutputStream();
multipartStream.readBodyData(data);
System.out.println(new String(data.toByteArray());
nextPart = multipartStream.readBoundary();
}
答案 2 :(得分:0)
对我来说,我使用这样的注释和参数:
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
<块引用>
公共响应 testUpload(文件上传输入流)
然后我可以读取文件内容:
byte[] totalBytes = Files.readAllBytes(Paths.get(uploadedInputStream.toURI()));
然后我必须忽略前 4 行,还有内容结尾部分,如下所示:
int headerLen = 0;
int index = 0;
while(totalBytes[index] != '\n' && index < totalBytes.length) {
headerLen++;
index++;
}
//ignore next three line
for (int i = 0; i < 3; i++) {
index++;
while (totalBytes[index] != '\n' && index < totalBytes.length) {
index++;
}
}
index++;
out.write(totalBytes, index, totalBytes.length - index - (headerLen+3));
out.flush();
out.close();