Я написал небольшое приложение, которое позволяло отправлять изображения, снятые камерой телефона, в базу данных. Вот как я решил эту вещь ...
public void writeCommentForRestaurant(int id, String comment, String author,
Bitmap image) {
if (image != null) {
/* Get the image as string */
// Normal
ByteArrayOutputStream full_stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, full_stream);
byte[] full_bytes = full_stream.toByteArray();
String img_full = Base64.encodeToString(full_bytes, Base64.DEFAULT);
// Thumbnail
ByteArrayOutputStream thumb_stream = new ByteArrayOutputStream();
// The getScaledBitmap method only minimizes the Bitmap to a small icon!
getScaledBitmap(image, 72).compress(Bitmap.CompressFormat.JPEG, 75,
thumb_stream);
byte[] thumb_bytes = thumb_stream.toByteArray();
String img_thumbnail = Base64.encodeToString(thumb_bytes, Base64.DEFAULT);
// new HTTPWorker(ctx, mHandler, HTTPWorker.WRITE_COMMENT, true).execute(
// Integer.toString(id), comment, author, img_thumbnail, img_full);
} else {
// new HTTPWorker(ctx, mHandler, HTTPWorker.WRITE_COMMENT, true).execute(
// Integer.toString(id), comment, author, null, null);
}
}
HTTPWorker - это просто асинхронная задача, которая создает метод HTTP.
...
/* Add arguments */
arguments.add(new BasicNameValuePair("idrestaurant", params[0]));
arguments.add(new BasicNameValuePair("comment", params[1]));
arguments.add(new BasicNameValuePair("author", params[2]));
if (params.length > 3) {
arguments.add(new BasicNameValuePair("image", params[3]));
arguments.add(new BasicNameValuePair("bigimage", params[4]));
}
...
А потом я отправил его на сервер вот так.
/**
* Executes a httppost to a server instance with the given POST arguments
* and returns a String response from the server.
*/
private String httppost(String url, ArrayList<NameValuePair> args) {
/* Create the channel for communicaton */
InputStream is = null;
/* Send request to server */
try {
/* Create the POST */
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
/* Add the login information "POST" variables in the php */
httppost.setEntity(new UrlEncodedFormEntity(args));
/* Execute the http POST and get the response */
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e(TAG, "Error in http connection " + e.toString());
return null;
}
/* Read response from server */
try {
/* Read the response stream */
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
/* Copy the response to StringBuilder */
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
/* Return the response as string */
return sb.toString();
} catch (Exception e) {
Log.e(TAG, "Error converting result " + e.toString());
return null;
}
}