Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload Bitmap Image from a android device?

Thank you in advance. I'd like to upload some bitmap image from my android app. but , I can't get it. Could you recommend some solutions for it. or collect my source code?

ByteArrayOutputStream bao = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        "http://example.com/imagestore/post");
                MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
                byte [] ba = bao.toByteArray();
                try {
                    entity.addPart("img", new StringBody(new String(bao.toByteArray())));
                    httppost.setEntity(entity);
                } catch (UnsupportedEncodingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                // Execute HTTP Post Request
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httppost);
                } catch (ClientProtocolException e) {
}
like image 359
freddiefujiwara Avatar asked Nov 03 '10 08:11

freddiefujiwara


2 Answers

use httpmime for uploading Image
try this
http://vikaskanani.wordpress.com/2011/01/11/android-upload-image-or-file-using-http-post-multi-part/

like image 121
augustine Avatar answered Oct 10 '22 08:10

augustine


I found this solution really well created and 100% working even with amazon ec2, take a look into this link:

Uploading files to HTTP server using POST on Android (link deleted).

Compare to previous answer, this solution doesn't require to import huge library httpmime from Apache.

Copied text from original article:

This tutorial shows a simple way of uploading data (images, MP3s, text files etc.) to HTTP/PHP server using Android SDK.

It includes all the code needed to make the uploading work on the Android side, as well as a simple server side code in PHP to handle the uploading of the file and saving it. Moreover, it also gives you information on how to handle the basic autorization when uploading the file.

When testing it on emulator remember to add your test file to Android’s file system via DDMS or command line.

What we are going to do is set the appropriate content type of the request and include the byte array as the body of the post. The byte array will contain the contents of a file we want to send to the server.

Below you will find a useful code snippet that performs the uploading operation. The code includes also server response handling.

HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "/data/file_to_send.mp3";
String urlServer = "http://192.168.1.1/handle_upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;

try
{
    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs.
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Set HTTP method to POST.
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

    outputStream = new DataOutputStream( connection.getOutputStream() );
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
    outputStream.writeBytes(lineEnd);

    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    outputStream.writeBytes(lineEnd);
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

    // Responses from the server (code and message)
    serverResponseCode = connection.getResponseCode();
    serverResponseMessage = connection.getResponseMessage();

    fileInputStream.close();
    outputStream.flush();
    outputStream.close();
}
catch (Exception ex)
{
    //Exception handling
}

If you need to authenticate your user with a username and password while uploading the file, the code snippet below shows how to add it. All you have to do is set the Authorization headers when the connection is created.

String usernamePassword = yourUsername + “:” + yourPassword;
String encodedUsernamePassword = Base64.encodeToString(usernamePassword.getBytes(), Base64.DEFAULT);
connection.setRequestProperty (“Authorization”, “Basic ” + encodedUsernamePassword);

Let’s say that a PHP script is responsible for receiving data on the server side. Sample of such a PHP script could look like this:

<?php
$target_path  = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
{
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
 " has been uploaded";
} 
else
{
    echo "There was an error uploading the file, please try again!";
}
?>;

Code was tested on Android 2.1 and 4.3. Remember to add permissions to your script on server side. Otherwise, the uploading won’t work.

chmod 777 uploadsfolder

Where uploadsfolder is the folder where the files are uploaded. If you plan to upload files bigger than default 2MB file size limit. You will have to modify the upload_max_filesize value in the php.ini file.

like image 36
dikirill Avatar answered Oct 10 '22 07:10

dikirill