在 android 中将多张图片上传到服务器的最佳方式是什么?
Which is the best way to upload multiple images to the server in android
我正在使用 okHttp 将多张图片(在本例中超过 10 张)上传到使用 multipartbody 的服务器。
我和我的朋友发生了争执,我说要在一个请求中上传所有图片。
他说一旦上一张图片上传上传下一张,一次发送一个请求。
这是正确的做法,所以服务器运行速度很快,不会发生超时。
您可以像下面这样发送 Base64 格式(字符串)并创建一个包含所有编码照片的文本文件作为字符串
/**
* Encodes the image to Base64.
*/
private String encodeImage(String photoPath) {
File imagefile = new File(photoPath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 80, baos);
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.DEFAULT);
}
并使用 MultipartUtility 上传文件:
我正在使用 okHttp 将多张图片(在本例中超过 10 张)上传到使用 multipartbody 的服务器。 我和我的朋友发生了争执,我说要在一个请求中上传所有图片。 他说一旦上一张图片上传上传下一张,一次发送一个请求。 这是正确的做法,所以服务器运行速度很快,不会发生超时。
您可以像下面这样发送 Base64 格式(字符串)并创建一个包含所有编码照片的文本文件作为字符串
/**
* Encodes the image to Base64.
*/
private String encodeImage(String photoPath) {
File imagefile = new File(photoPath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 80, baos);
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.DEFAULT);
}
并使用 MultipartUtility 上传文件: