gpt4 book ai didi

java - 将图像从 J2ME 客户端上传到 Servlet

转载 作者:太空宇宙 更新时间:2023-11-04 08:53:29 25 4
gpt4 key购买 nike

我想将图像从 J2ME 客户端发送到 Servlet。

我能够获取图像的字节数组并使用 HTTP POST 发送它。

conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
os.write(bytes, 0, bytes.length); // bytes = byte array of image

这是 Servlet 代码:

String line;
BufferedReader r1 = new BufferedReader(new InputStreamReader(in));
while ((line = r1.readLine()) != null) {
System.out.println("line=" + line);
buf.append(line);
}
String s = buf.toString();
byte[] img_byte = s.getBytes();

但是我发现的问题是,当我从 J2ME 客户端发送字节时,一些字节丢失了。它们的值为十六进制 0A0D。确切地说,是回车符和换行符。

因此,POST 方法或 readLine() 都无法接受 0A0D 值。

有人知道如何做到这一点,或者如何使用任何其他方法吗?

最佳答案

这是因为您使用 BufferedReader逐行读取二进制流。 readLine() 基本上分割 CRLF 上的内容。这些单独的行不再包含 CRLF。

不要对二进制流使用BufferedReader,它没有意义。只需将获得的InputStream写入任何风格的OutputStream,例如FileOutputStreamusual Java IO way .

InputStream input = null;
OutputStream output = null;

try {
input = request.getInputStream();
output = new FileOutputStream("/path/to/file.ext");

byte[] buffer = new byte[10240];
for (int length = 0; (length = input.read(buffer()) > 0;) {
output.write(buffer, 0, length);
}
} finally {
if (output != null) output.close();
if (input != null) input.close();
}
<小时/>

也就是说,您使用的 Content-Type 在技术上是错误的。您没有在请求正文中发送 WWW 形式的 URL 编码值。您正在发送二进制流。它应该是application/octet-stream或者image。这不是这个问题的原因,但它完全是错误的。

关于java - 将图像从 J2ME 客户端上传到 Servlet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2839208/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com