MattiahIT
MattiahIT

Reputation: 87

How to upload Image on Android?

I havve to upload image from my SD card to PHP server. I have read a lot of articles and topics but I have some problems...

First I have use that code:

HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    //DataInputStream inputStream = null;
    String urlServer = hostName+"Upload";
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";
    String serverResponseMessage;
    //int serverResponseCode;

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

    try
    {

        showLog("uploading file: " + file);

        FileInputStream fileInputStream = new FileInputStream(new File(pictureFileDir+"/"+file) );

        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=\"uploaded_file\";filename=\"" + file +"\"" + 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();

        showLog("server response: " + serverResponseMessage);

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

but server response 200/OK and no file was on destination server...

After i have read about Multipart:

try {
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        DefaultHttpClient mHttpClient = new DefaultHttpClient(params); 
        File image = new File(pictureFileDir + "/" + filename);
        HttpPost httppost = new HttpPost(hostName+"Upload");

        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
        multipartEntity.addPart("Image", new FileBody(image));
        httppost.setEntity(multipartEntity);

        mHttpClient.execute(httppost, new PhotoUploadResponseHandler());

    } catch (Exception e) {
       e.printStackTrace();
    }

but then a i have such LOG in LogCat and nothing else...

06-04 06:50:52.277: D/dalvikvm(1584): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueParser;.INSTANCE 06-04 06:50:52.277: W/dalvikvm(1584): VFY: unable to resolve static field 6688 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueParser; 06-04 06:50:52.277: D/dalvikvm(1584): VFY: replacing opcode 0x62 at 0x001b

ServerSide Script:

$target_path  = "uploads";
$target_path = $target_path . basename( $_FILES['Image']);
if(move_uploaded_file($_FILES['tmp_name'], $file_path)) {
    echo "success";
} else{
    echo "fail";
}

why? What is the simplest way to upload image?

Upvotes: 0

Views: 1681

Answers (3)

user2213590
user2213590

Reputation:

You'll need the httpmime and httpcore libraries for this code.

Then, do this:

try {
    MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
    mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(YOUR_ABSOLUTE_PATH_STRING);

    if (!file.exists())
        return null;

    mBuilder.addPart("mFile", new FileBody(file));
}

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost(YOUR_SERVER_URL);
httpPost.setEntity(mBuilder.build());

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();

//Reading the response:
InputStream is = httpEntity.getContent();

BufferedReader reader = new BufferedReader(
    new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;

while ((line = reader.readLine()) != null)
    sb.append(line + "\n");

is.close();
httpEntity.consumeContent();
//Do something with the string returned: sb.toString()

} catch (Exception e) {}

PHP Code

$fileName = uniqid() . ".png";
if (move_uploaded_file($_FILES["mFile"]["tmp_name"], "uploads/" . $fileName))
    return $fileName;
return "";

This code works for me, so if it doesn't work for you - check the image path you're sending, try a different image etc.

Upvotes: 1

MattiahIT
MattiahIT

Reputation: 87

OK finally everything work :) I have used that code:

try {
    showLog("uploading file: " + file);
    File image = new File(pictureFileDir + "/" + file);

    FileInputStream fileInputStream = new FileInputStream(image);

    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=\"" + pictureFileDir + "/" + file + "\"" + 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();

    showLog("server response: " + serverResponseMessage);

    image.delete();

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

and PHP script:

$target_path  = "uploads/";
$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!";
}

Thanks everyone :)

Upvotes: 0

ajitksharma
ajitksharma

Reputation: 2019

Try this,it is also using multipart, it worked for me.

try {
    String url = "<destination-path>";
    String fileName = ""; //file to be uploaded
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    FileBody fileContent = new FiSystem.out.println("hello");
    StringBody comment = new StringBody("Filename: " + fileName);
    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("file", fileContent);
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
}

Upvotes: 0

Related Questions