1. 程式人生 > >兩種android客戶端傳圖片的方法

兩種android客戶端傳圖片的方法

///////////2016/03/14///////////

/////////by  xbw/////////////////

/////////環境 eclipse php//

第一種,‘

一個類FileUtil

[java] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. package com.example.image_head;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.text.SimpleDateFormat;  
  7. import java.util.Date;  
  8. import java.util.Locale;  
  9. import android.content.Context;  
  10. import android.graphics.Bitmap;  
  11. import android.graphics.Bitmap.CompressFormat;  
  12. import android.os.Environment;  
  13. publicclass FileUtil {  
  14.     publicstatic String saveFile(Context c, String fileName, Bitmap bitmap) {  
  15.         return saveFile(c, 
    "", fileName, bitmap);  
  16.     }  
  17.     publicstatic String saveFile(Context c, String filePath, String fileName, Bitmap bitmap) {  
  18.         byte[] bytes = bitmapToBytes(bitmap);  
  19.         return saveFile(c, filePath, fileName, bytes);  
  20.     }  
  21.     publicstaticbyte[] bitmapToBytes(Bitmap bm) {  
  22.         ByteArrayOutputStream baos = new
     ByteArrayOutputStream();  
  23.         bm.compress(CompressFormat.JPEG, 100, baos);  
  24.         return baos.toByteArray();  
  25.     }  
  26.     publicstatic String saveFile(Context c, String filePath, String fileName, byte[] bytes) {  
  27.         String fileFullName = "";  
  28.         FileOutputStream fos = null;  
  29.         String dateFolder = new SimpleDateFormat("yyyyMMdd", Locale.CHINA)  
  30.                 .format(new Date());  
  31.         try {  
  32.             String suffix = "";  
  33.             if (filePath == null || filePath.trim().length() == 0) {  
  34.                 filePath = Environment.getExternalStorageDirectory() + "/JiaXT/" + dateFolder + "/";  
  35.             }  
  36.             File file = new File(filePath);  
  37.             if (!file.exists()) {  
  38.                 file.mkdirs();  
  39.             }  
  40.             File fullFile = new File(filePath, fileName + suffix);  
  41.             fileFullName = fullFile.getPath();  
  42.             fos = new FileOutputStream(new File(filePath, fileName + suffix));  
  43.             fos.write(bytes);  
  44.         } catch (Exception e) {  
  45.             fileFullName = "";  
  46.         } finally {  
  47.             if (fos != null) {  
  48.                 try {  
  49.                     fos.close();  
  50.                 } catch (IOException e) {  
  51.                     fileFullName = "";  
  52.                 }  
  53.             }  
  54.         }  
  55.         return fileFullName;  
  56.     }  
  57. }  
package com.example.image_head;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;

public class FileUtil {

   
	public static String saveFile(Context c, String fileName, Bitmap bitmap) {
		return saveFile(c, "", fileName, bitmap);
	}
	
	public static String saveFile(Context c, String filePath, String fileName, Bitmap bitmap) {
		byte[] bytes = bitmapToBytes(bitmap);
		return saveFile(c, filePath, fileName, bytes);
	}
	
	public static byte[] bitmapToBytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		bm.compress(CompressFormat.JPEG, 100, baos);
		return baos.toByteArray();
	}
	
	public static String saveFile(Context c, String filePath, String fileName, byte[] bytes) {
		String fileFullName = "";
		FileOutputStream fos = null;
		String dateFolder = new SimpleDateFormat("yyyyMMdd", Locale.CHINA)
				.format(new Date());
		try {
			String suffix = "";
			if (filePath == null || filePath.trim().length() == 0) {
				filePath = Environment.getExternalStorageDirectory() + "/JiaXT/" + dateFolder + "/";
			}
			File file = new File(filePath);
			if (!file.exists()) {
				file.mkdirs();
			}
			File fullFile = new File(filePath, fileName + suffix);
			fileFullName = fullFile.getPath();
			fos = new FileOutputStream(new File(filePath, fileName + suffix));
			fos.write(bytes);
		} catch (Exception e) {
			fileFullName = "";
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					fileFullName = "";
				}
			}
		}
		return fileFullName;
	}
}

第二個類 NetUtil

[java] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. package com.example.image_head;  
  2. import java.io.ByteArrayOutputStream;  
  3. import java.io.DataOutputStream;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.InputStream;  
  7. import java.net.URLEncoder;  
  8. import java.util.Iterator;  
  9. import java.util.Map;  
  10. import java.util.Set;  
  11. publicclass NetUtil {  
  12.     // 一般來說用一個生成一個UUID的話,會可靠很多,這裡就不考慮這個了
  13.     // 而且一般來說上傳檔案最好用BASE64進行編碼,你只要用BASE64不用的符號就可以保證不衝突了。
  14.     // 尤其是上傳二進位制檔案時,其中很可能有\r、\n之類的控制字元,有時還可能出現最高位被錯誤處理的問題,所以必須進行編碼。 
  15.     publicstaticfinal String BOUNDARY = "--my_boundary--";  
  16.     /** 
  17.      * 普通字串資料 
  18.      * @param textParams 
  19.      * @param ds 
  20.      * @throws Exception 
  21.      */
  22.     publicstaticvoid writeStringParams(Map<String, String> textParams,  
  23.             DataOutputStream ds) throws Exception {  
  24.         Set<String> keySet = textParams.keySet();  
  25.         for (Iterator<String> it = keySet.iterator(); it.hasNext();) {  
  26.             String name = it.next();  
  27.             String value = textParams.get(name);  
  28.             ds.writeBytes("--" + BOUNDARY + "\r\n");  
  29.             ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n");  
  30.             ds.writeBytes("\r\n");  
  31.             value = value + "\r\n";  
  32.             ds.write(value.getBytes());  
  33.         }  
  34.     }  
  35.     /** 
  36.      * 檔案資料 
  37.      * @param fileparams 
  38.      * @param ds 
  39.      * @throws Exception 
  40.      */
  41.     publicstaticvoid writeFileParams(Map<String, File> fileparams,   
  42.             DataOutputStream ds) throws Exception {  
  43.         Set<String> keySet = fileparams.keySet();  
  44.         for (Iterator<String> it = keySet.iterator(); it.hasNext();) {  
  45.             String name = it.next();  
  46.             File value = fileparams.get(name);  
  47.             ds.writeBytes("--" + BOUNDARY + "\r\n");  
  48.             //uploadedfile與伺服器端內容匹配
  49.             ds.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
  50.                     + URLEncoder.encode(value.getName(), "UTF-8") + "\"\r\n");  
  51.             ds.writeBytes("Content-Type:application/octet-stream \r\n");  
  52.             ds.writeBytes("\r\n");  
  53.             ds.write(getBytes(value));  
  54.             ds.writeBytes("\r\n");  
  55.         }  
  56.     }  
  57.     // 把檔案轉換成位元組陣列
  58.     privatestaticbyte[] getBytes(File f) throws Exception {  
  59.         FileInputStream in = new FileInputStream(f);  
  60.         ByteArrayOutputStream out = new ByteArrayOutputStream();  
  61.         byte[] b = newbyte[1024];  
  62.         int n;  
  63.         while ((n = in.read(b)) != -1) {  
  64.             out.write(b, 0, n);  
  65.         }  
  66.         in.close();  
  67.         return out.toByteArray();  
  68.     }  
  69.     /** 
  70.      * 新增結尾資料 
  71.      * @param ds 
  72.      * @throws Exception 
  73.      */
  74.     publicstaticvoid paramsEnd(DataOutputStream ds) throws Exception {  
  75.         ds.writeBytes("--" + BOUNDARY + "--" + "\r\n");  
  76.         ds.writeBytes("\r\n");  
  77.     }  
  78.     publicstatic String readString(InputStream is) {  
  79.         returnnew String(readBytes(is));  
  80.     }  
  81.     publicstaticbyte[] readBytes(InputStream is) {  
  82.         try {  
  83.             byte[] buffer = newbyte[1024];  
  84.             int len = -1;  
  85.             ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  86.             while ((len = is.read(buffer)) != -1) {  
  87.                 baos.write(buffer, 0, len);  
  88.             }  
  89.             baos.close();  
  90.             return baos.toByteArray();  
  91.         } catch (Exception e) {  
  92.             e.printStackTrace();  
  93.         }  
  94.         returnnull;  
  95.     }  
  96. }  
package com.example.image_head;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class NetUtil {

	// 一般來說用一個生成一個UUID的話,會可靠很多,這裡就不考慮這個了
	// 而且一般來說上傳檔案最好用BASE64進行編碼,你只要用BASE64不用的符號就可以保證不衝突了。
	// 尤其是上傳二進位制檔案時,其中很可能有\r、\n之類的控制字元,有時還可能出現最高位被錯誤處理的問題,所以必須進行編碼。 
	public static final String BOUNDARY = "--my_boundary--";

	/**
	 * 普通字串資料
	 * @param textParams
	 * @param ds
	 * @throws Exception
	 */
	public static void writeStringParams(Map<String, String> textParams,
			DataOutputStream ds) throws Exception {
		Set<String> keySet = textParams.keySet();
		for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
			String name = it.next();
			String value = textParams.get(name);
			ds.writeBytes("--" + BOUNDARY + "\r\n");
			ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n");
			ds.writeBytes("\r\n");
			value = value + "\r\n";
			ds.write(value.getBytes());

		}
	}

	/**
	 * 檔案資料
	 * @param fileparams
	 * @param ds
	 * @throws Exception
	 */
	public static void writeFileParams(Map<String, File> fileparams, 
			DataOutputStream ds) throws Exception {
		Set<String> keySet = fileparams.keySet();
		for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
			String name = it.next();
			File value = fileparams.get(name);
			ds.writeBytes("--" + BOUNDARY + "\r\n");
			//uploadedfile與伺服器端內容匹配
			ds.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
					+ URLEncoder.encode(value.getName(), "UTF-8") + "\"\r\n");
			ds.writeBytes("Content-Type:application/octet-stream \r\n");
			ds.writeBytes("\r\n");
			ds.write(getBytes(value));
			ds.writeBytes("\r\n");
		}
	}

	// 把檔案轉換成位元組陣列
	private static byte[] getBytes(File f) throws Exception {
		FileInputStream in = new FileInputStream(f);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int n;
		while ((n = in.read(b)) != -1) {
			out.write(b, 0, n);
		}
		in.close();
		return out.toByteArray();
	}

	/**
	 * 新增結尾資料
	 * @param ds
	 * @throws Exception
	 */
	public static void paramsEnd(DataOutputStream ds) throws Exception {
		ds.writeBytes("--" + BOUNDARY + "--" + "\r\n");
		ds.writeBytes("\r\n");
	}

	public static String readString(InputStream is) {
		return new String(readBytes(is));
	}

	public static byte[] readBytes(InputStream is) {
		try {
			byte[] buffer = new byte[1024];
			int len = -1;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while ((len = is.read(buffer)) != -1) {
				baos.write(buffer, 0, len);
			}
			baos.close();
			return baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}


方法,在button的點選事件中新增執行緒

[java] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. new Thread(uploadImageRunnable).start();  
new Thread(uploadImageRunnable).start();
[java] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. Runnable uploadImageRunnable = new Runnable() {  
  2.             @Override
  3.             publicvoid run() {  
  4.                 if(TextUtils.isEmpty(imgUrl)){//php伺服器端url
  5.                     Toast.makeText(getActivity(), "還沒有設定上傳伺服器的路徑!", Toast.LENGTH_SHORT).show();  
  6.                     return;  
  7.                 }  
  8.                 Map<String, String> textParams = new HashMap<String, String>();  
  9.                 Map<String, File> fileparams = new HashMap<String, File>();  
  10.                 try {  
  11.                     // 建立一個URL物件
  12.                     URL url = new URL(imgUrl);  
  13.                     textParams = new HashMap<String, String>();  
  14.                     fileparams = new HashMap<String, File>();  
  15.                     // 要上傳的圖片檔案
  16.                     File file = new File(urlpath);//本地圖片路徑
  17.                     fileparams.put("image", file);  
  18.                     // 利用HttpURLConnection物件從網路中獲取網頁資料
  19.                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  20.                     // 設定連線超時(記得設定連線超時,如果網路不好,Android系統在超過預設時間會收回資源中斷操作)
  21.                     conn.setConnectTimeout(5000);  
  22.                     // 設定允許輸出(傳送POST請求必須設定允許輸出)
  23.                     conn.setDoOutput(true);  
  24.                     // 設定使用POST的方式傳送
  25.                     conn.setRequestMethod("POST");  
  26.                     // 設定不使用快取(容易出現問題)
  27.                     conn.setUseCaches(false);  
  28.                     conn.setRequestProperty("Charset""UTF-8");//設定編碼   
  29.                     // 在開始用HttpURLConnection物件的setRequestProperty()設定,就是生成HTML檔案頭
  30.                     conn.setRequestProperty("ser-Agent""Fiddler");  
  31.                     // 設定contentType
  32.                     conn.setRequestProperty("Content-Type""multipart/form-data; boundary=" + NetUtil.BOUNDARY);  
  33.                     OutputStream os = conn.getOutputStream();  
  34.                     DataOutputStream ds = new DataOutputStream(os);  
  35.                     NetUtil.writeStringParams(textParams, ds);  
  36.                     NetUtil.writeFileParams(fileparams, ds);  
  37.                     NetUtil.paramsEnd(ds);  
  38.                     // 對檔案流操作完,要記得及時關閉
  39.                     os.close();  
  40.                     // 伺服器返回的響應嗎
  41.                     int code = conn.getResponseCode(); // 從Internet獲取網頁,傳送請求,將網頁以流的形式讀回來
  42.                     // 對響應碼進行判斷
  43.                     if (code == 200) {// 返回的響應碼200,是成功
  44.                         // 得到網路返回的輸入流
  45.                         InputStream is = conn.getInputStream();  
  46.                         resultStr = NetUtil.readString(is);  
  47.                     } else {  
  48.                         Toast.makeText(getActivity(), "請求URL失敗!", Toast.LENGTH_SHORT).show();  
  49.                     }  
  50.                 } catch (Exception e) {  
  51.                     e.printStackTrace();  
  52.                 }  
  53.                 handler.sendEmptyMessage(0);// 執行耗時的方法之後傳送消給handler
  54.             }  
  55.         };  
Runnable uploadImageRunnable = new Runnable() {
			@Override
			public void run() {
				if(TextUtils.isEmpty(imgUrl)){//php伺服器端url
					Toast.makeText(getActivity(), "還沒有設定上傳伺服器的路徑!", Toast.LENGTH_SHORT).show();
					return;
				}
				Map<String, String> textParams = new HashMap<String, String>();
				Map<String, File> fileparams = new HashMap<String, File>();
				try {
					// 建立一個URL物件
					URL url = new URL(imgUrl);
					textParams = new HashMap<String, String>();
					fileparams = new HashMap<String, File>();
					// 要上傳的圖片檔案
					File file = new File(urlpath);//本地圖片路徑
					fileparams.put("image", file);
					// 利用HttpURLConnection物件從網路中獲取網頁資料
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					// 設定連線超時(記得設定連線超時,如果網路不好,Android系統在超過預設時間會收回資源中斷操作)
					conn.setConnectTimeout(5000);
					// 設定允許輸出(傳送POST請求必須設定允許輸出)
					conn.setDoOutput(true);
					// 設定使用POST的方式傳送
					conn.setRequestMethod("POST");
					// 設定不使用快取(容易出現問題)
					conn.setUseCaches(false);
					conn.setRequestProperty("Charset", "UTF-8");//設定編碼   
					// 在開始用HttpURLConnection物件的setRequestProperty()設定,就是生成HTML檔案頭
					conn.setRequestProperty("ser-Agent", "Fiddler");
					// 設定contentType
					conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + NetUtil.BOUNDARY);
					OutputStream os = conn.getOutputStream();
					DataOutputStream ds = new DataOutputStream(os);
					NetUtil.writeStringParams(textParams, ds);
					NetUtil.writeFileParams(fileparams, ds);
					NetUtil.paramsEnd(ds);
					// 對檔案流操作完,要記得及時關閉
					os.close();
					// 伺服器返回的響應嗎
					int code = conn.getResponseCode(); // 從Internet獲取網頁,傳送請求,將網頁以流的形式讀回來
					// 對響應碼進行判斷
					if (code == 200) {// 返回的響應碼200,是成功
						// 得到網路返回的輸入流
						InputStream is = conn.getInputStream();
						resultStr = NetUtil.readString(is);
					} else {
						Toast.makeText(getActivity(), "請求URL失敗!", Toast.LENGTH_SHORT).show();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendEmptyMessage(0);// 執行耗時的方法之後傳送消給handler
			}
		};
[java] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
</pre><div class="dp-highlighter bg_java"><div class="bar"><div class="tools"><strong>[java]</strong> <a target=_blank title="view plain" class="ViewSource" href="http://blog.csdn.net/xbw12138/article/details/50890255#">view plain</a><span data-mod="popu_168"> <a target=_blank title="copy" class="CopyToClipboard" href="http://blog.csdn.net/xbw12138/article/details/50890255#">copy</a></span><div style="left: 421px; top: 5638px; width: 18px; height: 18px; position: absolute; z-index: 99;"></div><span data-mod="popu_169"> <a target=_blank title="print" class="PrintSource" href="http://blog.csdn.net/xbw12138/article/details/50890255#">print</a></span><a target=_blank title="?" class="About" href="http://blog.csdn.net/xbw12138/article/details/50890255#">?</a><span class="tracking-ad" data-mod="popu_167"><a target=_blank title="在CODE上檢視程式碼片" style="text-indent:0;" href="https://code.csdn.net/snippets/1610066" target="_blank"><img width="12" height="12" style="position:relative;top:1px;left:2px;" alt="在CODE上檢視程式碼片" src="https://code.csdn.net/assets/CODE_ico.png" /></a></span><span class="tracking-ad" data-mod="popu_170"><a target=_blank title="派生到我的程式碼片" style="text-indent:0;" href="https://code.csdn.net/snippets/1610066/fork" target="_blank"><img width="12" height="12" style="position:relative;top:2px;left:2px;" alt="派生到我的程式碼片" src="https://code.csdn.net/assets/ico_fork.svg" /></a></span></div></div><ol class="dp-j"><li class="alt"><span><span>Handler handler = </span><span class="keyword">new</span><span> Handler(</span><span class="keyword">new</span><span> Handler.Callback() {  </span></span></li><li><span>   <span class="annotation">@Override</span><span>  </span></span></li><li class="alt"><span>   <span class="keyword">public</span><span> </span><span class="keyword">boolean</span><span> handleMessage(Message msg) {  </span></span></li><li><span>    <span class="keyword">switch</span><span> (msg.what) {  </span></span></li><li class="alt"><span>    <span class="keyword">case</span><span> </span><span class="number">0</span><span>:  </span></span></li><li><span>     <span class="comment">//dialogs.dismiss();</span><span>  </span></span></li><li class="alt"><span>     <span class="keyword">try</span><span> {  </span></span></li><li><span>      <span class="comment">// 返回資料示例,根據需求和後臺資料靈活處理</span><span>  </span></span></li><li class="alt"><span>       </span></li><li><span>      JSONObject jsonObject = <span class="keyword">new</span><span> JSONObject(resultStr);  </span></span></li><li class="alt"><span>       String imageUrl = jsonObject.optString(<span class="string">"imageUrl"</span><span>);  </span></span></li><li><span>       Toast.makeText(getActivity(), imageUrl, Toast.LENGTH_SHORT).show();  </span></li><li class="alt"><span>      }<span class="keyword">else</span><span>{  </span></span></li><li><span>       Toast.makeText(getActivity(), jsonObject.optString(<span class="string">"statusMessage"</span><span>), Toast.LENGTH_SHORT).show();  </span></span></li><li class="alt"><span>      }  </span></li><li><span>        </span></li><li class="alt"><span>     } <span class="keyword">catch</span><span> (JSONException e) {  </span></span></li><li><span>      e.printStackTrace();  </span></li><li class="alt"><span>     }  </span></li><li><span>       </span></li><li class="alt"><span>     <span class="keyword">break</span><span>;  </span></span></li><li><span>       </span></li><li class="alt"><span>    <span class="keyword">default</span><span>:  </span></span></li><li><span>     <span class="keyword">break</span><span>;  </span></span></li><li class="alt"><span>    }  </span></li><li><span>    <span class="keyword">return</span><span> </span><span class="keyword">false</span><span>;  </span></span></li><li class="alt"><span>   }  </span></li><li><span>  });  </span></li></ol><div class="save_code tracking-ad" style="display: none;" data-mod="popu_249"><a target=_blank target="_blank"><img src="http://static.blog.csdn.net/images/save_snippets.png" alt="" /></a></div></div><pre class="java" style="display: none;" name="code" code_snippet_id="1610066" snippet_file_name="blog_20160314_6_9143161">Handler handler = new Handler(new Handler.Callback() {
   @Override
   public boolean handleMessage(Message msg) {
    switch (msg.what) {
    case 0:
     //dialogs.dismiss();
     try {
      // 返回資料示例,根據需求和後臺資料靈活處理
     
      JSONObject jsonObject = new JSONObject(resultStr);
       String imageUrl = jsonObject.optString("imageUrl");
       Toast.makeText(getActivity(), imageUrl, Toast.LENGTH_SHORT).show();
      }else{
       Toast.makeText(getActivity(), jsonObject.optString("statusMessage"), Toast.LENGTH_SHORT).show();
      }
      
     } catch (JSONException e) {
      e.printStackTrace();
     }
     
     break;
     
    default:
     break;
    }
    return false;
   }
  });

這樣就好了

第二種。

在button監聽事件中新增

[java] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. new Task().execute();  
new Task().execute();
[java] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. class Task extends AsyncTask<String, Integer, Integer> {  
  2.             @Override
  3.             protected Integer doInBackground(String... strings) {  
  4.                 Integer result = -1;  
  5.                 try {  
  6.                     result = UpFile.post(config_a.uploadUrl,  
  7.                      new File("/storage/extSdCard/b.png"));//本地圖片路徑
  8.                 }  
  9.                 catch (IOException e) {  
  10.                     e.printStackTrace();  
  11.                 }  
  12.                 return result;  
  13.             }  
  14.             @Override
  15.             protectedvoid onPostExecute(Integer result) {  
  16.                 Toast.makeText(getActivity(), "" + result, Toast.LENGTH_LONG).show();  
  17.             }  
  18.         }  
class Task extends AsyncTask<String, Integer, Integer> {

			@Override
			protected Integer doInBackground(String... strings) {
				Integer result = -1;
				try {
					result = UpFile.post(config_a.uploadUrl,
					 new File("/storage/extSdCard/b.png"));//本地圖片路徑
				}
				catch (IOException e) {
					e.printStackTrace();
				}
				return result;
			}
			@Override
			protected void onPostExecute(Integer result) {
				Toast.makeText(getActivity(), "" + result, Toast.LENGTH_LONG).show();
			}
		}
Upload_image.java類 [java] view plain copy print?在CODE上檢視程式碼片派生到我的程式碼片
  1. package com.example.image_head;  
  2. import java.io.BufferedReader;  
  3. import java.io.DataOutputStream;  
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.net.HttpURLConnection;  
  10. import java.net.URL;  
  11. import java.util.UUID;  
  12. import com.example.configs.config_a;  
  13. import android.widget.Toast;  
  14. publicclass Upload_image {  
  15.     publicstaticclass UpFile {  
  16.         publicstaticint post(String actionUrl, File file) throws IOException {  
  17.             //產生隨機分隔內容
  18.             String BOUNDARY = UUID.randomUUID().toString();  
  19.             String PREFIX = "--";  
  20.             String LINEND = "\r\n";  
  21.             String MULTIPART_FROM_DATA = "multipart/form-data";  
  22.             String CHARSET = "UTF-8";  
  23.             URL url = new URL(actionUrl);  
  24.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  25.             //設定超時時間單位是毫秒
  26.             conn.setReadTimeout(5 * 1000);  
  27.             //設定允許輸入
  28.             conn.setDoInput(true);  
  29.             //設定允許輸出
  30.             conn.setDoOutput(true);  
  31.             //不允許使用快取
  32.             conn.setUseCaches(false);  
  33.             //設定請求的方法為Post
  34.             conn.setRequestMethod("POST");  
  35.             //設定維持長連線
  36.             conn.setRequestProperty("Connection""keep-alive");  
  37.             //設定字符集為UTF-8
  38.             conn.setRequestProperty("Charset", CHARSET);  
  39.             //設定檔案的型別
  40.             conn.setRequestProperty("Content-type", MULTIPART_FROM_DATA + "; boundary=" + BOUNDARY);  
  41.             DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());  
  42.             //傳送檔案資料
  43.             if (file != null) {  
  44.                 StringBuilder sb = new StringBuilder();  
  45.                 sb.append(PREFIX);  
  46.                 sb.append(BOUNDARY);  
  47.                 sb.append(LINEND);  
  48.                 //uploadedfile與伺服器端內容匹配
  49.                 sb.append("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"" + file.getName() + "\"" + LINEND);  
  50.                 //
  51.                 sb.append("Content-Type: image/png"  + LINEND);  
  52.                 sb.append(LINEND);  
  53.                 //寫入輸出流中
  54.                 outStream.write(sb.toString().getBytes());  
  55.                 //將檔案讀入輸入流中
  56.                 InputStream is = new FileInputStream(file);  
  57.                 byte[] buffer = newbyte[1024];  
  58.                 int len = -1;  
  59.                 //寫入輸出流中
  60.                 while ((len = is.read(buffer)) != -1) {  
  61.                     outStream.write(buffer, 0, len);  
  62.                 }  
  63.                 is.close();  
  64.                 //新增換行標識
  65.                 outStream.write(LINEND.getBytes());  
  66.             }  
  67.             byte[] endData = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();  
  68.             outStream.write(endData);  
  69.             //傳送資料
  70.             outStream.flush();  
  71.             //獲取響應碼 上傳成功返回的是200
  72.             int res = conn.getResponseCode();  
  73.             return res;  
  74.         }  
  75.     }  
  76. }  
package com.example.image_head;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOExcep