天天看點

Android檔案上傳至伺服器

項目示範及講解 

優酷  http://v.youku.com/v_show/id_XODk5NjkwOTg4.html

愛奇藝  http://www.iqiyi.com/w_19rs1v2m15.html#vfrm=8-7-0-1

洋芋  http://www.tudou.com/programs/view/fv0H93IHfhM

項目下載下傳

1、手機端選擇檔案上傳至伺服器端

http://download.csdn.net/detail/u010134178/8457679

2、手機端拍照上傳至伺服器端

http://download.csdn.net/detail/u010134178/8457673

3、總下載下傳位址

http://down.51cto.com/7851921/up

這些都是需要積分的,如果積分不夠的話發送到我郵箱[email protected]我直接把項目發送過來

大家在調試的同時一定要注意

1、網絡下載下傳、上傳這些操作,就是耗時的操作,要另外開線程操作,不能放到主線程裡面。

2、網絡下載下傳、上傳裡面不能有ui操作,不能在裡面顯示ui。就是不能在子線程裡面操作UI。如果操作完畢ui提示使用者等操作,可以使用利用handler結合Thread更新UI,或者AsyncTask異步更新UI。

3、上傳到本地Tomcat伺服器,要關閉防火牆

接下來将給出兩個項目部分代碼,當然兩個項目都有一個工具類HttpPost

public class HttpPost {
	/**
	 * 通過拼接的方式構造請求内容,實作參數傳輸以及檔案傳輸
	 * 
	 * @param acti
	 *            .nUrl
	 * @param params
	 * @param files
	 * @return
	 * @throws IOException
	 */
	public static String post(String actionUrl, Map<String, String> params, Map<String, File> files) throws IOException {

		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";

		URL uri = new URL(actionUrl);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(5 * 1000); // 緩存的最長時間
		conn.setDoInput(true);// 允許輸入
		conn.setDoOutput(true);// 允許輸出
		conn.setUseCaches(false); // 不允許使用緩存
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);

		// 首先組拼文本類型的參數
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> entry : params.entrySet()) {
			sb.append(PREFIX);
			sb.append(BOUNDARY);
			sb.append(LINEND);
			sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
			sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
			sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
			sb.append(LINEND);
			sb.append(entry.getValue());
			sb.append(LINEND);
		}

		DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
		outStream.write(sb.toString().getBytes());
		// 發送檔案資料
		if (files != null)
			for (Map.Entry<String, File> file : files.entrySet()) {
				StringBuilder sb1 = new StringBuilder();
				sb1.append(PREFIX);
				sb1.append(BOUNDARY);
				sb1.append(LINEND);
				sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\"" + LINEND);
				sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
				sb1.append(LINEND);
				outStream.write(sb1.toString().getBytes());

				InputStream is = new FileInputStream(file.getValue());
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = is.read(buffer)) != -1) {
					outStream.write(buffer, 0, len);
				}

				is.close();
				outStream.write(LINEND.getBytes());
			}

		// 請求結束标志
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();
		// 得到響應碼
		int res = conn.getResponseCode();
		InputStream in = conn.getInputStream();
		if (res == 200) {
			int ch;
			StringBuilder sb2 = new StringBuilder();
			while ((ch = in.read()) != -1) {
				sb2.append((char) ch);
			}
		}
		outStream.close();
		conn.disconnect();
		return in.toString();

	}

}      
public void uploadPhoto() {
		
		Map<String, String> params = new HashMap<String, String>();
		params.put("strParamName", "strParamValue");
		Map<String, File> files = new HashMap<String, File>();
		files.put(System.currentTimeMillis()+".jpg", new File(uploadFile));//uploadFile = "/sdcard/AnBo/laolisb.jpg";
		try {
			String str = HttpPost.post(actionUrl, params, files);
			System.out.println("str--->>>" + str);
		} catch (Exception e) {
		}
	}      
/******************************************************/
		private String fun(String msg){
		int i = msg.length();
		int j = msg.lastIndexOf("/") + 1;
		
		String a = msg.substring(j, i) ;
		System.out.println(a);
		return a;
		}
	/******************************************************/

	private void uploadFile() {
		show.setVisibility(View.VISIBLE);
		new Thread() {
			@Override
			public void run() {

				Message msg = Message.obtain();
				
				// 伺服器的通路路徑
				String uploadUrl = "http://192.168.0.104:8080/UploadPhoto1/UploadServlet";
				Map<String, File> files = new HashMap<String, File>();
				
				String name = fun(picturePath);
				files.put(name, new File(picturePath));
				//files.put("test.jpg", new File(picturePath));
				Log.d("str--->>>", picturePath);
				try {
					String str = HttpPost.post(uploadUrl, new HashMap<String,String>(), files);
					System.out.println("str--->>>" + str);
					msg.what = SUCCESS;
				} catch (Exception e) {
					msg.what = FAILD;
				}
				mHandler.sendMessage(msg);
				
			}
		}.start();
	}