Simulator Screenshots



In this example uploading an image from sdcard to web server.
Steps :
1. place an image on sdcard.
2. place sdcard image path and image name in UploadToServer.java. ( see below )
3. create a php script (UploadToServer.php) at server. ( see below )
4. place php script path in UploadToServer.java. ( see below )
5. create folder name uploads on server where you have placed php script.
6. give permission 777 (read/write/execute) to uploads folder.
Project Structure :
Upload Image Sdcard View :
File : AndroidManifest.xml
<? xml version = "1.0" encoding = "utf-8" ?> package = "com.androidexample.uploadtoserver" android:versionCode = "1" android:versionName = "1.0" > < uses-sdk android:minSdkVersion = "8" /> < uses-permission android:name = "android.permission.INTERNET" /> < application android:allowBackup = "true" android:icon = "@drawable/ic_launcher" android:label = "@string/app_name" android:theme = "@style/AppTheme" > < activity android:name = "com.androidexample.uploadtoserver.UploadToServer" android:label = "@string/app_name" > < intent-filter > < action android:name = "android.intent.action.MAIN" /> < category android:name = "android.intent.category.LAUNCHER" /> </ intent-filter > </ activity > </ application > </ manifest > |
File : res/layout/activity_upload_to_server.xml
<? xml version = "1.0" encoding = "utf-8" ?> android:orientation = "vertical" android:layout_width = "fill_parent" android:layout_height = "fill_parent" > < Button android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:text = "Click To Upload File" android:id = "@+id/uploadButton" /> < TextView android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:text = "" android:id = "@+id/messageText" android:textColor = "#000000" android:textStyle = "bold" /> </ LinearLayout > |
File : src/UploadToServer.java
import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.app.ProgressDialog; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class UploadToServer extends Activity { TextView messageText; Button uploadButton; int serverResponseCode = 0 ; ProgressDialog dialog = null ; String upLoadServerUri = null ; /********** File Path *************/ final String uploadFilePath = "/mnt/sdcard/" ; final String uploadFileName = "service_lifecycle.png" ; @Override public void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_upload_to_server); uploadButton = (Button)findViewById(R.id.uploadButton); messageText = (TextView)findViewById(R.id.messageText); messageText.setText( "Uploading file path :- '/mnt/sdcard/" +uploadFileName+ "'" ); /************* Php script path ****************/ uploadButton.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { dialog = ProgressDialog.show(UploadToServer. this , "" , "Uploading file..." , true ); new Thread( new Runnable() { public void run() { runOnUiThread( new Runnable() { public void run() { messageText.setText( "uploading started....." ); } }); uploadFile(uploadFilePath + "" + uploadFileName); } }).start(); } }); } public int uploadFile(String sourceFileUri) { String fileName = sourceFileUri; HttpURLConnection conn = null ; DataOutputStream dos = null ; String lineEnd = "\r\n" ; String twoHyphens = "--" ; String boundary = "*****" ; int bytesRead, bytesAvailable, bufferSize; byte [] buffer; int maxBufferSize = 1 * 1024 * 1024 ; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { dialog.dismiss(); Log.e( "uploadFile" , "Source File not exist :" +uploadFilePath + "" + uploadFileName); runOnUiThread( new Runnable() { public void run() { messageText.setText( "Source File not exist :" +uploadFilePath + "" + uploadFileName); } }); return 0 ; } else { try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); conn.setDoInput( true ); // Allow Inputs conn.setDoOutput( true ); // Allow Outputs conn.setUseCaches( false ); // Don't use a Cached Copy conn.setRequestMethod( "POST" ); conn.setRequestProperty( "Connection" , "Keep-Alive" ); conn.setRequestProperty( "ENCTYPE" , "multipart/form-data" ); conn.setRequestProperty( "Content-Type" , "multipart/form-data;boundary=" + boundary); conn.setRequestProperty( "uploaded_file" , fileName); dos = new DataOutputStream(conn.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes( "Content-Disposition: form-data; name=" uploaded_file ";filename=" " + fileName + "" " + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte [bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0 , bufferSize); while (bytesRead > 0 ) { dos.write(buffer, 0 , bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0 , bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = conn.getResponseCode(); String serverResponseMessage = conn.getResponseMessage(); Log.i( "uploadFile" , "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 200 ){ runOnUiThread( new Runnable() { public void run() { String msg = "File Upload Completed.\n\n See uploaded file here : \n\n" +uploadFileName; messageText.setText(msg); Toast.makeText(UploadToServer. this , "File Upload Complete." , Toast.LENGTH_SHORT).show(); } }); } //close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { dialog.dismiss(); ex.printStackTrace(); runOnUiThread( new Runnable() { public void run() { messageText.setText( "MalformedURLException Exception : check script url." ); Toast.makeText(UploadToServer. this , "MalformedURLException" , Toast.LENGTH_SHORT).show(); } }); Log.e( "Upload file to server" , "error: " + ex.getMessage(), ex); } catch (Exception e) { dialog.dismiss(); e.printStackTrace(); runOnUiThread( new Runnable() { public void run() { messageText.setText( "Got Exception : see logcat " ); Toast.makeText(UploadToServer. this , "Got Exception : see logcat " , Toast.LENGTH_SHORT).show(); } }); Log.e( "Upload file to server Exception" , "Exception : " + e.getMessage(), e); } dialog.dismiss(); return serverResponseCode; } // End else block } } |
Php script at server :
File : UploadToServer.php
<?php $file_path = "uploads/" ; $file_path = $file_path . basename ( $_FILES [ 'uploaded_file' ][ 'name' ]); if (move_uploaded_file( $_FILES [ 'uploaded_file' ][ 'tmp_name' ], $file_path )) { echo "success" ; } else { echo "fail" ; } ?> |
Show uploaded image at server :
'STUDY' 카테고리의 다른 글
파이썬 코드 조각모음 (0) | 2013.12.07 |
---|---|
[PHP] Json encode/decode (0) | 2013.08.19 |
sublime TEXT2 - sftp 설정 (0) | 2013.08.13 |
Upload File To Server - Android Example (0) | 2013.08.10 |
[Android] 안드로이드 개발 환경 구축 (1) | 2013.08.05 |
Apache Struts2 보안취약점을 이용한 원격 중요정보 유출 공지 (0) | 2013.07.25 |
안드로이드의 기본 Language 는 JAVA이다. 하여 가장 먼저 JAVA를 설치하여야 한다.
설치 순 : JDK 설치 -> 이클립스(개발 툴) 설치 -> 이클립스 내부 ADT 설치 -> SDK 매니저 설치 -> SDK 매니저로 플랫폼 추가
1. JAVA 설치
- JAVA 기본 설치를 위해 ORACLE 홈페이지에서 Java Platform (JDK) 를 설치하야 한다.
링크 : http://www.oracle.com/technetwork/java/javase/downloads/index.html
다음 JDK 를 선택 한 후 "Accept License Agreement"를 선택하고 다음과 같이 운영체제의 버전에 맞게 설치를 한다.
2. 이클립스 설치
- 이클립스 설치는 설치가 아니라 해당 파일을 받은 후 압축만 풀면 JDK 가 깔린 상태에서 싱행되기 때문에 별도의 설치는 필요가 없다. 보통 [[ Eclipse IDE for Java EE Developers, 246 MB ]] 를 설치하면 된다.
링크 : http://www.eclipse.org/downloads/
3. ADT 설치
- 이클립스 실행 후, Help - Install New Software 를 선택, Install 창에서 Add버튼을 클릭 후 다음과 같이 빈칸을 채운다.
Name : Android-ADT
Location: https://dl-ssl.google.com/android/eclipse
※ 만약 되지 않을경우 https:// 에서 http:// 로 바꿔보도록 한다.
그 후 Developer Tools 와 NDK Plugins 를 선택 한 다음 Next 신공을 누르고 'I accept the terms of the license agreements' 를 선택하여 설치를 Finish한다.
다음과 같이 설치가 완료되었으면 이클립스를 다시 실행한다는 경고창이 뜨게 된다. 그 후 다시 시작하면 ADT의 설치는 끝난다.
4. SDK 설치 및 SDK 매니저로 플랫폼 추가
- 수동적인 방법으로 해당 링크에 들어가서 USE AN EXISTING IDE 에 들어가서 해당 SDK Tools 를 다운받는다.
링크 : http://developer.android.com/sdk/index.html
Download the SDK Tools for Windows 다운로드
다운로드한 위치에 SDK Manage를 실행하거나 Window - Android SDK Manager 를 눌러 버전별로 플랫폼을 다운받을 수 있다.
설치 진행 중 에러메시지가 나오면 yes를 눌러주면 된다.
5. 에뮬레이터 생성하기
- 이클립스 실행 후 Window - Android Virtual Device Manager를 클릭해 New로 에뮬레이터를 만들 수 있다.
'STUDY' 카테고리의 다른 글
파이썬 코드 조각모음 (0) | 2013.12.07 |
---|---|
[PHP] Json encode/decode (0) | 2013.08.19 |
sublime TEXT2 - sftp 설정 (0) | 2013.08.13 |
Upload File To Server - Android Example (0) | 2013.08.10 |
[Android] 안드로이드 개발 환경 구축 (1) | 2013.08.05 |
Apache Struts2 보안취약점을 이용한 원격 중요정보 유출 공지 (0) | 2013.07.25 |