据我所知,Volley 并不是将大量数据(如图像)发送到远程服务器的正确选择。无论如何,如果你想发送图像,你应该扩展 Request 类并实现你的逻辑。
您可以以工具箱包中已有的一些类为例。
否则,您可以使用 HttpURLConnection 并实现您的逻辑,首先您必须设置:
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
其中边界是您喜欢的字符串。
然后你必须从连接获取输出流并开始编写你的部分。
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());
}
等等。
我写了一篇关于它的教程(因为您正在询问链接)。你可以给看一下here.
如果您不喜欢 HttpUrlConnection,您可以更轻松地使用 Apache Http 客户端。
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
进而:
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
希望对您有帮助!