1.加入權限AndroidManifest.xml
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2.加入三個檔案放在lib資料夾下
httpclient-4.3.6.jar
httpcore-4.3.3.jar
httpmime-4.3.6.jar
3./res/layout/main.xml
4.建立檔案AndroidMultiPartEntity.java
import java.io.FilterOutputStream; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; @SuppressWarnings("deprecation") public class AndroidMultiPartEntity extends MultipartEntity { private final ProgressListener listener; public AndroidMultiPartEntity(final ProgressListener listener) { super(); this.listener = listener; } public AndroidMultiPartEntity(final HttpMultipartMode mode, final ProgressListener listener) { super(mode); this.listener = listener; } public AndroidMultiPartEntity(HttpMultipartMode mode, final String boundary, final Charset charset, final ProgressListener listener) { super(mode, boundary, charset); this.listener = listener; } @Override public void writeTo(final OutputStream outstream) throws IOException { super.writeTo(new CountingOutputStream(outstream, this.listener)); } public static interface ProgressListener { void transferred(long num); } public static class CountingOutputStream extends FilterOutputStream { private final ProgressListener listener; private long transferred; public CountingOutputStream(final OutputStream out, final ProgressListener listener) { super(out); this.listener = listener; this.transferred = 0; } public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); this.transferred += len; this.listener.transferred(this.transferred); } public void write(int b) throws IOException { out.write(b); this.transferred++; this.listener.transferred(this.transferred); } } }5.主檔Main.java
import java.io.File; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; 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.content.FileBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import tw.android.AndroidMultiPartEntity.ProgressListener; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; public class Main extends Activity { private ProgressBar progressBar; private String FILE_UPLOAD_URL,filePath = null; private TextView txtPercentage; private Button btnUpload; long totalSize = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtPercentage = (TextView) findViewById(R.id.txtPercentage); btnUpload = (Button) findViewById(R.id.btnUpload); progressBar = (ProgressBar) findViewById(R.id.progressBar); /*上傳server網址*/ FILE_UPLOAD_URL= "http://xxxxx.3eeweb.com/AndroidFileUpload/fileUpload.php"; String folder="life"; //資料夾名稱 String fileName="IMG_20150226_161243.jpg"; //要上傳的手機裡的檔案-檔案名稱 filePath = "/storage/sdcard0/"+folder+"/"+fileName; // 檔案路徑位置 /*上傳按鈕*/ btnUpload.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // 上傳至後端sever new UploadFileToServer().execute(); } }); } /* 上傳至後端sever */ private class UploadFileToServer extends AsyncTask6.後端php接收檔案/AndroidFileUpload/fileUpload.php{ /* 背景執行前的顯示動作 */ @Override protected void onPreExecute() { // 設定進度條初始為0 progressBar.setProgress(0); super.onPreExecute(); } /* 背景執行中的顯示動作 */ @Override protected void onProgressUpdate(Integer... progress) { // 顯示進度條 progressBar.setVisibility(View.VISIBLE); // 更新進度療 progressBar.setProgress(progress[0]); // 更新顯示文字百分比 txtPercentage.setText(String.valueOf(progress[0]) + "%"); } /* 背景執行的工作 */ @Override protected String doInBackground(Void... params) { return uploadFile(); } @SuppressWarnings("deprecation") private String uploadFile() { String responseString = null; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(FILE_UPLOAD_URL); try { AndroidMultiPartEntity entity = new AndroidMultiPartEntity( new ProgressListener() { public void transferred(long num) { publishProgress((int) ((num / (float) totalSize) * 100)); } }); File sourceFile = new File(filePath); // Adding file data to http body entity.addPart("image", new FileBody(sourceFile)); /* 攜帶參數(非必要) */ // Extra parameters if you want to pass to server // entity.addPart("website", // new StringBody("www.androidhive.info")); // entity.addPart("email", new StringBody("abc@gmail.com")); totalSize = entity.getContentLength(); httppost.setEntity(entity); // Making server call HttpResponse response = httpclient.execute(httppost); HttpEntity r_entity = response.getEntity(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { // Server response responseString = EntityUtils.toString(r_entity); } else { responseString = "Error occurred! Http Status Code: " + statusCode; } } catch (ClientProtocolException e) { responseString = e.toString(); } catch (IOException e) { responseString = e.toString(); } return responseString; } /* 背景執行完成後的顯示動作 */ @Override protected void onPostExecute(String result) { Log.e("END", "Response from server: " + result); /* 完成後alert顯示訊息 */ showAlert(result); super.onPostExecute(result); } } /* 完成後alert顯示訊息 */ private void showAlert(String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(message).setTitle("Response from Servers") .setCancelable(false) .setPositiveButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // do nothing } }); AlertDialog alert = builder.create(); alert.show(); } }
檔案會上傳至/AndroidFileUpload/uploads/
echo $_FILES['image']['name'] . '< br/>'; //ini_set('upload_max_filesize', '10M'); //ini_set('post_max_size', '10M'); //ini_set('max_input_time', 300); //ini_set('max_execution_time', 300); $target_path = "uploads/"; $target_path = $target_path . basename($_FILES['image']['name']); try { //throw exception if can't move the file if (!move_uploaded_file($_FILES['image']['tmp_name'], $target_path)) { throw new Exception('Could not move file'); } echo "The file " . basename($_FILES['image']['name']) . " has been uploaded"; } catch (Exception $e) { die('File did not upload: ' . $e->getMessage()); }
檔案下載:
app:https://github.com/terryyamg/uploadTest
php:https://drive.google.com/file/d/0BxoUMTbigRuCZnVyM3VTV2o2NVU/view?usp=sharing
推薦後端網頁:http://cpanel.2freehosting.com/
參考來源:http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/
沒有留言 :
張貼留言