package com.example.upload;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
//import android.util.Base64;
import com.example.upload.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.io.Reader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main extends Activity {
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private ImageView img;
//EditText ed=(EditText)findViewById(R.id.ed);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img = (ImageView)findViewById(R.id.ImageView01);
((Button) findViewById(R.id.Button01)).setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
//選擇圖片
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
//最後一個參數傳入選擇圖片的URI
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
InputStream is;
//data去接剛剛選取的圖片
if (resultCode == RESULT_OK)
{
if (requestCode == SELECT_PICTURE)
{
//取得路徑
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
//設定顯示圖片
img.setImageURI(selectedImageUri);
//使用Bitmap取圖片
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
//圖片寬高都為原來的二分之一,即圖片為原來的四分之一
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath,options);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte [] ba = bao.toByteArray();
//要POST至PHP檔使用Base64編碼
String ba1=Base64.encodeBytes(ba);
final ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("source",ba1));
try{
/*
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://127.0.0.1/SOT/upload.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
*/
//好像都不能直接跑在主執行緒上因此直接做了Thread讓他去用
Thread thread = new Thread(){
@Override
public void run(){
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("YOUR_URL");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
//設定輸出為UTF-8
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
}catch (Exception e){
e.printStackTrace();
}finally{
}
}
};
//開始執行執行緒
thread.start();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
}
}
}
public String getPath(Uri uri)
{ String[] projection =
{
MediaStore.Images.Media.DATA
};
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public String convertStreamToString(InputStream is)
throws IOException {
//
// To convert the InputStream to String we use the
// Reader.read(char[] buffer) method. We iterate until the
// Reader return -1 which means there's no more data to
// read. We use the StringWriter class to produce the string.
//
if (is != null) {
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
} else {
return "";
}
}
}
PHP檔如下:
$base=$_REQUEST['source'];
echo $base;
// base64 encoded utf-8 string
$binary=base64_decode($base);
// binary, utf-8 bytes
header('Content-Type: bitmap; charset=utf-8');
$name=uniqid();
//uniqid()是用來亂數產生一串英文數字
$file = fopen("$name.jpg", 'wb');
//開啟以那串英文數字為檔名的檔案
fwrite($file, $binary);
//寫入檔案
fclose($file);
//寫入完畢關閉檔案
//unlink($file)
//unlink刪除檔案
echo "";
大部分的解釋都直接註解在裡面了
這是一個從Android選取圖片直接上傳到PHP的程式
花了不少時間拼拼湊湊才把這個弄出來
網路上資料雖然很多,但是很多都是不能用的,不然就是舊的...
以上的流程大概就是
Android -> choose image -> encode(use Base64) -> PHP($_REQUEST) -> decode(Base64)
->Write to File and save
下面這兩行是因為手機似乎不像電腦有那麼大的記憶體
如果不縮小一點常常都會出現java.lang.outmemory然後就直接Shutdown了...
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
然後
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
如果要傳中文進去php檔必須要記得php檔要用utf儲存
android端送出資料的時候也要記得加上HTTP.UTF_8
如果出現這一行
org.apache.http.conn.HttpHostConnectException: Connection to http://127.0.0.1 refused
上網google似乎是因為android把自己當作local端了..
所以只要用 cmd ipconfig 查詢本機的ip換上去就可以了通常是 192.168.xxx.xxx
沒有留言:
張貼留言