Android上傳文件到Web服務器,PHP接收文件

package com.tianlei.httpUrlConnection_PHPUpload;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

public class Upload{
	/** Called when the activity is first created. */
	/**
	 * Upload file to web server with progress status, client: android;
	 * server:php
	 * **/
	private String urlServer = "http://120.126.16.52/uploadfile.php";  //the server address to process the uploaded file
	public String filepath;   //the file path to upload
	private Context c;
	public Upload(Context c, String filepath){
		this.c = c;
		this.filepath = filepath;
	}
	//開始下載並顯示進度條
    public void startUpload(){
    	FileUploadTask fileUploadTask = new FileUploadTask();
    	fileUploadTask.execute();
    }
	// show Dialog method
	/*private void showDialog(String mess) {
		new AlertDialog.Builder(c).setTitle("Message")
				.setMessage(mess)
				.setNegativeButton("肯定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				}).show();
	}*/

	class FileUploadTask extends AsyncTask<Object, Integer, Void> {

		private ProgressDialog dialog = null;
		
		HttpURLConnection connection = null;
		DataOutputStream outputStream = null;
		DataInputStream inputStream = null;
		
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		
		File uploadFile = new File(filepath);
		long totalSize = uploadFile.length(); // Get size of file, bytes

		/*該方法將在執行實際的後臺操做前被UI thread調用。能夠在該方法中作一些準備工做,
		 * 如在界面上顯示一個進度條。 */
		@Override
		protected void onPreExecute() {
			dialog = new ProgressDialog(c);
			dialog.setMessage("正在上傳...");
			dialog.setIndeterminate(false);
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setProgress(0);
			dialog.show();
		}

		/*將在onPreExecute 方法執行後立刻執行,該方法運行在後臺線程中。這裏將主要負責執行
		 * 那些很耗時的後臺計算工做。能夠調用 publishProgress方法來更新實時的任務進度。
		 * 該方法是抽象方法,子類必須實現。*/
		@Override
		protected Void doInBackground(Object... arg0) {

			long length = 0;
			int progress;
			int bytesRead, bytesAvailable, bufferSize;
			byte[] buffer;
			int maxBufferSize = 256 * 1024;// 256KB

			try {
				FileInputStream fileInputStream = new FileInputStream(new File(
						filepath));

				URL url = new URL(urlServer);
				connection = (HttpURLConnection) url.openConnection();

				// Set size of every block for post
				connection.setChunkedStreamingMode(256 * 1024);// 256KB

				// Allow Inputs & Outputs
				connection.setDoInput(true);
				connection.setDoOutput(true);
				connection.setUseCaches(false);

				// Enable POST method
				connection.setRequestMethod("POST");
				connection.setRequestProperty("Connection", "Keep-Alive");
				connection.setRequestProperty("Charset", "UTF-8");
				connection.setRequestProperty("Content-Type",
						"multipart/form-data;boundary=" + boundary);

				outputStream = new DataOutputStream(
						connection.getOutputStream());
				outputStream.writeBytes(twoHyphens + boundary + lineEnd);
				outputStream
						.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
								+ filepath + "\"" + lineEnd);
				outputStream.writeBytes(lineEnd);

				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				buffer = new byte[bufferSize];

				// Read file
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);

				while (bytesRead > 0) {
					outputStream.write(buffer, 0, bufferSize);
					length += bufferSize;
					progress = (int) ((length * 100) / totalSize);
					//調用 publishProgress方法來更新實時的任務進度
					publishProgress(progress);

					bytesAvailable = fileInputStream.available();
					bufferSize = Math.min(bytesAvailable, maxBufferSize);
					bytesRead = fileInputStream.read(buffer, 0, bufferSize);
				}
				outputStream.writeBytes(lineEnd);
				outputStream.writeBytes(twoHyphens + boundary + twoHyphens
						+ lineEnd);
				//進度條100,下載完成
				publishProgress(100);

				/*經過使用Dialog()對話框顯示進度條*/
				
				// Responses from the server (code and message)
				//int serverResponseCode = connection.getResponseCode();
				//String serverResponseMessage = connection.getResponseMessage();

				/* 將Response顯示於Dialog */
				// Toast toast = Toast.makeText(UploadtestActivity.this, ""
				// + serverResponseMessage.toString().trim(),
				// Toast.LENGTH_LONG);
				// showDialog(serverResponseMessage.toString().trim());
				/* 取得Response內容 */
				// InputStream is = connection.getInputStream();
				// int ch;
				// StringBuffer sbf = new StringBuffer();
				// while ((ch = is.read()) != -1) {
				// sbf.append((char) ch);
				// }
				//
				// showDialog(sbf.toString().trim());

				fileInputStream.close();
				outputStream.flush();
				outputStream.close();

			} catch (Exception ex) {
				// Exception handling
				// showDialog("" + ex);
				// Toast toast = Toast.makeText(UploadtestActivity.this, "" +
				// ex,
				// Toast.LENGTH_LONG);
			}
			return null;
		}
		
		/*在publishProgress方法被調用後,UI thread將調用這個方法從而在界面上展現任務
		 *的進展狀況,例如經過一個進度條進行展現。*/
		@Override
		protected void onProgressUpdate(Integer... progress) {
			dialog.setProgress(progress[0]);
		}
		/*在doInBackground 執行完成後,onPostExecute 方法將被UI thread調用,
		 *後臺的計算結果將經過該方法傳遞到UI thread.*/
		@Override
		protected void onPostExecute(Void result) {
			try {
				dialog.dismiss();  //dismiss the dialog
				// TODO Auto-generated method stub
			} catch (Exception e) {
			}
		}

	}
}
相關文章
相關標籤/搜索