开发者

Upload image from J2ME client to a Servlet

I want to send an image from a J2ME client to a Servlet.

I am able to get a byte array of the image and send it using 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

This is the Servlet code:

String line;
BufferedReader r1 = new BufferedReader(new InputStreamReader(in));
while ((line = r1.r开发者_C百科eadLine()) != null) {
    System.out.println("line=" + line);
    buf.append(line);
}
String s = buf.toString();
byte[] img_byte = s.getBytes();

But the problem I found is, when I send bytes from the J2ME client, some bytes are lost. Their values are 0A and 0D hex. Exactly, the Carriage Return and Line Feed.

Thus, either POST method or readLine() are not able to accept 0A and 0D values.

Any one have any idea how to do this, or how to use any another method?


That's because you're using a BufferedReader to read the binary stream line by line. The readLine() basically splits the content on CRLF. Those individual lines doesn't contain the CRLF anymore.

Don't use the BufferedReader for binary streams, it doesn't make sense. Just write the obtained InputStream to an OutputStream of any flavor, e.g. FileOutputStream, the usual 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();
}

That said, the Content-Type you're using is technically wrong. You aren't sending a WWW-form URL-encoded value in the request body. You are sending a binary stream. It should be application/octet-stream or maybe image. This is not the cause of this problem, but it is just plain wrong.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜