patternjavaMinor
File to String Pattern for uploading to a server
Viewed 0 times
fileuploadingforserverstringpattern
Problem
I need to upload some images to a server. This is done with a json object. The json object has 2 values, a timestamp and a Base64 encoded string of the image. I am using the jackson library and was wondering if this is a good way to upload the images. I am worried about memory consumption if I happen to upload images asyncronusly in the future. Here is is...
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Photo {
@JsonIgnore
private String path;
private String id;
@JsonProperty("ts")
private long timestamp;
public Photo(long timestamp, String path) {
this.timestamp = timestamp;
this.path = path;
}
public String getData() {
Bitmap bm = BitmapFactory.decodeFile(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, baos);
bm.recycle();
byte[] byteArray = baos.toByteArray();
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}
}Solution
I'm not familiar with Android at all, so just some generic Java notes:
-
I'd rename
-
The constructor should validate its input parameters. Does it make sense to call it with
-
It is a bad idea to use
-
I don't know if it differs from general Java or not but closing a
-
I'd rename
bm to bitmap. A little bit longer variable names are usually easier to read and maintain.-
The constructor should validate its input parameters. Does it make sense to call it with
null or empty string as path or a less than zero timestamp? If not, check it and throw a NullPointerException or an IllegalStateException. (Effective Java, Second Edition, Item 38: Check parameters for validity)-
It is a bad idea to use
printStackTrace() in Android exceptions.-
I don't know if it differs from general Java or not but closing a
ByteArrayOutputStream in Java has no effect. You might be able to omit it.Context
StackExchange Code Review Q#17680, answer score: 2
Revisions (0)
No revisions yet.