Upload image to server from Blackberry

独自空忆成欢 提交于 2020-01-17 08:05:13

问题


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:


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
}


来源:https://stackoverflow.com/questions/7793354/upload-image-to-server-from-blackberry

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!