How to upload a bitmap image to server using android volley library?

六月ゝ 毕业季﹏ 提交于 2019-12-18 17:56:40

问题


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


回答1:


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!




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/19980832/how-to-upload-a-bitmap-image-to-server-using-android-volley-library

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