Skip to content Skip to sidebar Skip to footer

Uploading Image To Server - Android

I have got the Rest Api's link and the sample code for uploading the image in C sharp but how to upload image to server from android the same thing using java Here's that sample co

Solution 1:

I am currently using this code to upload small videos to server (PHP server side).

Take not that the apache HttpClient is not supported anymore, so HttpURLConnection is the way to go.

try {
        FileInputStreamfileInputStream=newFileInputStream(newFile(
                path));

        URLurl=newURL(urlLink);
        connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setRequestMethod("POST");

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

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

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

        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);

        fileInputStream.close();
        outputStream.flush();
        outputStream.close();

        InputStreamresponseStream=newBufferedInputStream(connection.getInputStream());

        BufferedReaderresponseStreamReader=newBufferedReader(newInputStreamReader(responseStream));
        Stringline="";
        StringBuilderstringBuilder=newStringBuilder();
        while ((line = responseStreamReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        responseStreamReader.close();

        Stringresponse= stringBuilder.toString();
        Log.w("SERVER RESPONE: ", response);

        responseStream.close();
        connection.disconnect();

    } catch (Exception ex) {
        Log.i("UPLOAD ERROR", "ERROR ERROR");
    }
}

Solution 2:

here is the PHP that may help you for receiving the file on your server.

<?phptry {


    // Checking for upload attack and rendering invalid.if (
        !isset($_FILES['uploadedfile']['error']) ||
        is_array($_FILES['uploadedfile']['error'])
    ) {
        thrownewRuntimeException('Invalid parameters.');
    }

    // checking for error value on uploadswitch ($_FILES['uploadedfile']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:
            thrownewRuntimeException('No file sent.');
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            thrownewRuntimeException('Exceeded filesize limit.');
        default:
            thrownewRuntimeException('Unknown errors.');
    }

    // checking file size if ($_FILES['uploadedfile']['size'] > 1000000) {
        thrownewRuntimeException('Exceeded filesize limit.');
    }


    // checking MIME type for mp4... change this to suit your needs$finfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search(
        $finfo->file($_FILES['uploadedfile']['tmp_name']),
        array(
            'mp4' => 'video/mp4',
        ),
        true
    )) {
        thrownewRuntimeException('Invalid file format.');
    }


    // Uniquely naming each uploaded for fileif (!move_uploaded_file(
        $_FILES['uploadedfile']['tmp_name'],
        sprintf('./uploads/%s.%s',
            sha1_file($_FILES['uploadedfile']['tmp_name']),
            $ext
        )
    )) {
        thrownewRuntimeException('Failed to move uploaded file.');
    }
    // response code.echo'File is uploaded successfully!';

}
catch (RuntimeException$e) {

    echo$e->getMessage();

}

?>

Solution 3:

try this....

publicstaticJSONObjectpostFile(String url,String filePath,int id){

String result="";
HttpClient httpClient = newDefaultHttpClient();
HttpPost httpPost = newHttpPost(url);

File file = newFile(filePath);
MultipartEntity mpEntity = newMultipartEntity();
ContentBody cbFile = newFileBody(file, "image/jpeg");

StringBody stringBody= null;
JSONObject responseObject=null;

try {
    stringBody = newStringBody(id+"");
    mpEntity.addPart("file", cbFile);
    mpEntity.addPart("id",stringBody);
    httpPost.setEntity(mpEntity);
    System.out.println("executing request " + httpPost.getRequestLine());
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity resEntity = response.getEntity();
    result=resEntity.toString();
    responseObject=newJSONObject(result);
} 
catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} 
catch (ClientProtocolException e) {
    e.printStackTrace();
} 
catch (IOException e) {
    e.printStackTrace();
} 
catch (JSONException e) {
    e.printStackTrace();
}
return responseObject;
}

Post a Comment for "Uploading Image To Server - Android"