我需要一个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文件中写入字节。附言:文件的发送者不是我。
发布于 2012-07-14 19:30:44
Apache commons解决了90%的问题...只需要知道在搜索中使用什么关键字:)
"parse multipart request“和谷歌说: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();
}发布于 2012-07-13 22:26:10
我不知道您为什么不使用HttpServletRequest的getInputStream()方法来获取没有头的内容,无论哪种方式,您都可以选择开始读取输入流并忽略内容,直到找到两个连续的CRLF,它定义了头的结尾。
这样做的一种方法是:
String headers = new java.util.Scanner(inputStream).next("\\r\\n\\r\\n");
// Read rset of input stream发布于 2021-04-16 12:25:44
对于我来说,我使用的注释和参数如下:
@Consumes(MediaType.APPLICATION_OCTET_STREAM)公共响应testUpload(文件uploadedInputStream)
然后,我可以使用以下命令读取文件内容:
 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();https://stackoverflow.com/questions/11471822
复制相似问题