Upload image to server from Blackberry

2019-08-30 06:17发布

I am trying to send an image to server. I converted the image to a byte array. I then tried the code from "HTTP Post multipart file upload in Java ME" on the Nokia developer forums.

I also tried the code from "HTTP POST and passing parameters in URLs" on the BlackBerry forums.

I am passing parameters and getting response code 200. But image is not sent to the server. I am stuck on this.

1条回答
来,给爷笑一个
2楼-- · 2019-08-30 07:07
try{

FileConnection fis=(FileConnection)Connector.open(filename);
InputStream inputStream = fis.openInputStream();

ByteArrayOutputStream bos=new ByteArrayOutputStream();
int buffersize=1024;
byte[] buffer=new byte[buffersize];
int length=0;
while((length=inputStream.read(buffer))!=-1)
{
    bos.write(buffer,0,length);
}
byte[] imagedata=bos.toByteArray();

HttpConnection conn = (HttpConnection) Connector.open(Url, Connector.READ_WRITE);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE,                    
    HttpProtocolConstants.CONTENT_TYPE_MULTIPART_FORM_DATA
                        + ";boundary=" + boundary);

    conn.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH,
                String.valueOf(imagedata.length));
conn.setRequestProperty("x-rim-transcode-content", "none");

ByteArrayOutputStream out = new ByteArrayOutputStream();
OutputStream finalOut = conn.openOutputStream();

String newLine = "\r\n";
out.write(newLine.getBytes());
out.write("--".getBytes());
out.write(boundary.getBytes());
out.write(newLine.getBytes());
String contDisp = "Content-Disposition:form-data;  
    name=\"file\";filename=\"Image.jpg\"";
String contEnc = "Content-Transfer-Encoding: binary";
String type = "Content-Type:image/jpeg";
out.write(contDisp.getBytes());
out.write(newLine.getBytes());
out.write(type.getBytes());
out.write(newLine.getBytes());
out.write(contEnc.getBytes());
out.write(newLine.getBytes());
out.write(newLine.getBytes());
out.write(imagedata);
out.write(newLine.getBytes());
out.write("--".getBytes());
out.write(boundary.getBytes());
out.write("--".getBytes());
out.write(newLine.getBytes());
finalOut.write(out.toByteArray());

out.flush();
out.close();

finalOut.flush();
finalOut.close();
InputStream instream=conn.openInputStream();
int ch=0;
StringBuffer buffesr=new StringBuffer();
while((ch=instream.read())!=-1)
{
    buffesr.append((char)ch);
}



catch (Exception e) {
    // TODO: handle exception
}
查看更多
登录 后发表回答