How to upload a bitmap image to server using android volley library ?I am trying to use android volley to upload images to server . If there is no such option in android volley ,can you please suggest me the best way to make networking actions faster. You are welcome to message me the links to any available tutorials online pertaining to this subject

有帮助吗?

解决方案

As far as I know, Volley isn't the right choice to send a large amount of data (like an image) to a remote server. Anyway, if you want to send an image you should extend Request class and implements your logic. You could take as an example some classes already available in the toolbox package. Otherwise, You can use HttpURLConnection and implement your logic, first you have to set:

con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

where boundary is a string you like. Then you have to get the output stream from connection and start writing your parts.

public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
  os.write( (delimiter + boundary + "\r\n").getBytes());
  os.write( ("Content-Disposition: form-data; name=\"" + paramName +  "\";    filename=\"" + fileName + "\"\r\n"  ).getBytes());
  os.write( ("Content-Type: application/octet-stream\r\n"  ).getBytes());
  os.write( ("Content-Transfer-Encoding: binary\r\n"  ).getBytes());
  os.write("\r\n".getBytes());

  os.write(data);

  os.write("\r\n".getBytes());
}

And so on. I wrote a tutorial about it (since you are asking a link). You can give a look here.

If you don't like HttpUrlConnection you can use more easily Apache Http client.

HttpClient client = new DefaultHttpClient(); 
HttpPost post = new HttpPost(url); 

and then:

MultipartEntity multiPart = new MultipartEntity();
multiPart.addPart("param1", new StringBody(param1)); 
multiPart.addPart("param2", new StringBody(param2)); 
multiPart.addPart("file", new ByteArrayBody(baos.toByteArray(), "logo.png")); // Your image

Hope it helps you!

其他提示

You could extends a subclass of Request ,and override the getBody() method, and return image's byte data in the getBody() method.

Image can be sent to server using volley lib without using Multipart class. You just need to send the image in base64 format to server. It worked for me.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top