1. 程式人生 > >Android簡單實現將手機圖片上傳到server中

Android簡單實現將手機圖片上傳到server中

sdk etc mov 創建 ast bmi 以及 lena ews

在本例中。將會簡單的實現安卓手機將圖片上傳到server中。本例使用到了 server端:PHP+APACHE 客戶端:JAVA 先簡單實現一下server端的上傳並測試上傳效果,看實例
<?php if(empty($_GET[‘submit‘])){?>
<form enctype="multipart/form-data" action="<?php $_SERVER[‘PHP_SELF‘]?

>?submit=1" method="post"> Send this file: <input name="filename" type="file"> <input type="submit" value="確定上傳"> </form> <?

php }else{ $path="E:\ComsenzEXP\wwwroot\uploadfiles/"; if(!file_exists($path)){mkdir("$path", 0700);} $file2 = $path.time().".jpg"; $result = move_uploaded_file($_FILES["filename"]["tmp_name"],$file2); if($result){ $return = array( ‘status‘=>‘true‘, ‘path‘=>$file2 ); }else{ $return = array( ‘status‘=>‘false‘, ‘path‘=>$file2 ); } echo json_encode($return); } ?>

在上述代碼中非常easy的就已經將圖片上傳到server中,同一時候須要註意的是,在真實的操作過程中,這段代碼是不能夠直接拿來用的,須要對其進行很多其它的功能擴展,比方說驗證圖片是否同意上傳,驗證圖片大小等等。 接下來,再看一下Android主程序 MainActivity.java
package com.example.androidupload;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
private String imagePath;//將要上傳的圖片路徑
private Handler handler;//將要綁定到創建他的線程中(通常是位於主線程)
private MultipartEntity multipartEntity;
private Boolean isUpload = false;//推斷是否上傳成功
private TextView tv;
private String sImagePath;//server端返回路徑

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagePath = Environment.getExternalStorageDirectory() + File.separator
+ "tmp.jpg";

handler = new Handler();//綁定到主線程中
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new Thread() {
public void run() {
File file = new File(imagePath);
multipartEntity = new MultipartEntity();
ContentBody contentBody = new FileBody(file,
"image/jpeg");
multipartEntity.addPart("filename", contentBody);
HttpPost httpPost = new HttpPost(
"http://192.168.1.100/x.php?submit=1");
httpPost.setEntity(multipartEntity);
HttpClient httpClient = new DefaultHttpClient();
try {
HttpResponse httpResponse = httpClient
.execute(httpPost);
InputStream in = httpResponse.getEntity()
.getContent();
String content = readString(in);
int httpStatus = httpResponse.getStatusLine()
.getStatusCode();//獲取通信狀態
if (httpStatus == HttpStatus.SC_OK) {
JSONObject jsonObject = parseJSON(content);//解析字符串為JSON對象
String status = jsonObject.getString("status");//獲取上傳狀態
sImagePath = jsonObject.getString("path");
Log.d("MSG", status);
if (status.equals("true")) {
isUpload = true;
}
}
Log.d("MSG", content);
Log.d("MSG", "Upload Success");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.post(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
if (isUpload) {
tv = (TextView)findViewById(R.id.textView1);
tv.setText(sImagePath);
Toast.makeText(MainActivity.this, "上傳成功",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "上傳失敗",
Toast.LENGTH_SHORT).show();
}
}
});
}
}.start();
}
});

}

protected String readString(InputStream in) throws Exception {
byte[] data = new byte[1024];
int length = 0;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
while ((length = in.read(data)) != -1) {
bout.write(data, 0, length);
}
return new String(bout.toByteArray(), "GBK");
}

protected JSONObject parseJSON(String str) {
JSONTokener jsonParser = new JSONTokener(str);
JSONObject result = null;
try {
result = (JSONObject) jsonParser.nextValue();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}
由於是簡單實現,也能更通俗的理解,這裏並沒有對操作網絡以及通用函數進行封裝,所以能夠直接拷貝此段代碼到自己的應用程序中進行略微的改動就能夠直接執行,在這裏定義的server返回路徑能夠自己改動為URL路徑,這樣能夠在返回的Activity中我們能夠實現將剛才上傳成功的照片顯示在客戶端中,以下再看一下布局文件 activity_main.xml
<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"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="19dp"
android:layout_marginTop="36dp"
android:text="Button" />

</RelativeLayout>
最好,就是權限問題了。由於操作了網絡,所以不能忘記將INTERNET權限加上,看一下 AndroidMainFest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidupload"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />

<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.example.androidupload.MainActivity"
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>
這樣來說,就能夠使用手機將圖片上傳到server中了。

Android簡單實現將手機圖片上傳到server中