我需要将图像从我的 Android 应用程序发送到 Google App Engine 数据存储区。此图像需要作为Blob
数据类型嵌入到JSONObject
.
我能够从设备摄像头捕获图像并将其压缩为 jpg 格式。然后我使用ByteArrayOutputStream
fromBitmap.compress()
方法创建一个字节数组。
问题是,我如何将(put()
/ accumulate()
)这个字节数组放入JSONObject
. 我尝试了以下方法,即将字节数组转换为JSONArray
private JSONObject createJSONObject() {
byte[] bryPhoto = null;
ByteArrayInputStream bais = null;
ByteArrayOutputStream baos = null;
JSONArray jryPhoto = null;
JSONObject jbjToBeSent = null;
baos = new ByteArrayOutputStream();
jbjToBeSent = new JSONObject();
try {
jbjToBeSent.accumulate("hwBatch", strBatch);
jbjToBeSent.accumulate("hwDescription", etDescription.getText().toString());
if(null == bmpPhoto) {
bryPhoto = null;
}
else {
bmpPhoto.compress(Bitmap.CompressFormat.JPEG, 10, baos);
bryPhoto = baos.toByteArray();
bais = new ByteArrayInputStream(bryPhoto);
}
jryPhoto = readBytes(bais);
jbjToBeSent.accumulate("hwPhoto", jryPhoto);
}
catch(JSONException je) {
// Omitted exception handling code to improve readability
}
return jbjToBeSent;
}
public JSONArray readBytes(InputStream inputStream) {
JSONArray array = null;
try {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
array = new JSONArray();
int len = 0;
int i = 0;
while ((len = inputStream.read(buffer)) != -1) {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
byteBuffer.write(buffer, 0, len);
byte[] b= byteBuffer.toByteArray();
array.put(i,Base64.encodeToString(b, Base64.DEFAULT));
i++;
}
}
catch(IOException ioe) {
// Omitted exception handling code to improve readability
}
catch(JSONException jsone) {
// Omitted exception handling code to improve readability
}
return array;
}
这在服务器端失败并出现错误:
Expected BEGIN_OBJECT but was BEGIN_ARRAY。我知道我在做什么是错误的,但是,在 a 中嵌入字节数组的正确方法是JSONObject
什么?
编辑:我知道 Blobstore,这将是我最后的手段。我试图完成这项工作并不是为了规避 Blobstore。