Here we see how to upload a file on server.
In order to upload a file on server we need a server , but
here we create a local server either by installing wamp or xampp. To access
localhost from android emulator use address http://10.0.2.2/.
Note: Put tuts4mobile_upload.png (find it in
project ) into your
android emulator.
Create a project with the following details :
- ProjectName: UploadFile
- PackageName: sat.tuts4mobile.uploadfile
- ActivityName: UploadActivity
In the UploadActivity.java , copy and paste the
following code:
package
sat.tuts4mobile.uploadfile;
import
android.app.Activity;
import
android.os.Bundle;
import
android.view.Menu;
import
android.view.View;
import
android.widget.Toast;
public
class UploadActivity extends Activity {
String imageUrl;
String uploadUrl;
@Override
protected
void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
imageUrl
= "/mnt/sdcard/tuts4mobile_upload.png";
uploadUrl
= "http://10.0.2.2/upoadandroid/upload.php";
findViewById(R.id.buttonUpload).setOnClickListener(new
View.OnClickListener() {
@Override
public
void onClick(View v) {
//
TODO
Auto-generated method stub
String responce = new ServerRequest().uploadFile(uploadUrl,
imageUrl);
Toast.makeText(UploadActivity.this, responce,Toast.LENGTH_SHORT).show();
}
});
}
@Override
public
boolean onCreateOptionsMenu(Menu
menu) {
//
Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.upload, menu);
return
true;
}
}
Create a new class name ServerRequest.java , and copy paste
the following code:
package
sat.tuts4mobile.uploadfile;
import
java.io.BufferedReader;
import
java.io.DataOutputStream;
import
java.io.File;
import
java.io.FileInputStream;
import
java.io.InputStream;
import
java.io.InputStreamReader;
import
java.net.HttpURLConnection;
import
java.net.MalformedURLException;
import
java.net.URL;
import
android.util.Log;
public
class ServerRequest {
public
String uploadFile(String upLoadServerUri, String sourceFileUri) {
StringBuffer response = null;
int
serverResponseCode = 0;
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);
{
try
{
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.setChunkedStreamingMode(1024);
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=\"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)
{
System.out.println("Done
Send to Server !!!");
InputStream is =
conn.getInputStream();
BufferedReader rd = new BufferedReader(
new
InputStreamReader(is));
String line;
response = new StringBuffer();
while
((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
}
//
close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch
(MalformedURLException ex) {
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch
(Exception e) {
Log.e("Upload file to server Exception",
"Exception
: " + e.getMessage(), e);
}
return
response.toString();
} //
End else block
}
}
In the activity_upload.xml file ,copy and paste the following code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".UploadActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Note: Before upload make sure that you put
(tuts4mobile_upload.png) file in the sdcard of emulator. You find (
tuts4mobile_upload.png ) file in the project folder." />
<Button
android:id="@+id/buttonUpload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Click to upload" />
</RelativeLayout>
In the AndroidManifest.xml file , copy and paste the following
code:
<?xml version="1.0"
encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sat.tuts4mobile.uploadfile"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="14" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="sat.tuts4mobile.uploadfile.UploadActivity"
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>
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
After doing this , create a folder name “uploadandroid” in your local server directory .
If you are using xampp
then in “htdocs” or for wamp in “www”.
Now create a file in “uploadandroid” folder with name “upload.php” and paste the
following code:
<?php
$tmpfile=$_FILES["file"]["tmp_name"];
$size=$_FILES["file"]["size"];
$filename=basename($_FILES["file"]["name"]);
$type=$_FILES["file"]["type"];
$destination="uploads";
$file_upload=move_uploaded_file
( $tmpfile
,$destination."/".$filename );
if($file_upload)
{
echo "Upload Successfully !!!";
}
?>
And also create a folder name “uploads”.
Now run the application , it shows the following screen
shots:
hi i am facing peer unverified ssl exception. how did you solve this?
ReplyDeletecan you please help me out?
Wonderful work I have ever read. Content written is up to the mark and quality is just incredible. Find the Mobile application development company in india. Visit OnGraph technologies.
ReplyDeleteHey nice blog,Thanks for this helpful information come back again for more interesting information…Keep it up! .
ReplyDeleteMobile Application Development and Brevity Software
Good Job ! I enjoyed enough reading your latest article to read it again and again! It was so helpful. Waiting for your next entry .
ReplyDeleteHire HTML5 Developers
thank u for Review
ReplyDelete