標籤:data gets ora 沒有 圖片 rate ttext view get
在本例中。將會簡單的實現安卓手機將圖片上傳到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端返迴路徑@Overrideprotected 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() {@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubnew 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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}handler.post(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubif (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 blocke.printStackTrace();}return result;}@Overridepublic 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" ><TextViewandroid: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" /><Buttonandroid: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-sdkandroid:minSdkVersion="8"android:targetSdkVersion="16" /><uses-permission android:name="android.permission.INTERNET" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid: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中