Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 系列:POST 圖片上傳的實作

編輯:Android 開發實例

這幾天一直在想 Android 上怎麼把圖片 POST 到伺服器,今天總算寫出一個能跑的小 DEMO。整個流程可以拆成三段:拍照取得圖檔、壓縮、以 multipart 方式上傳。

一、拍照並在子執行緒中上傳

 1  private void imageClient(){
 2
 3      fileName = UUID.randomUUID().toString();
 4
 5      try{
 6          Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 7          imgFile = new File(Environment.getExternalStorageDirectory(), fileName + ".jpg");
 8          Uri outputFileUri = Uri.fromFile(imgFile);
 9          cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
10          startActivityForResult(cameraIntent, 10);
11      } catch (Exception ex) {
12          ex.printStackTrace();
13          Log.e("EP", "" + ex.getMessage());
14      }
15  }
16
17  @Override
18  protected void onActivityResult(int requestCode, int resultCode, Intent data){
19      super.onActivityResult(requestCode, resultCode, data);
20
21      switch (resultCode) {
22      case RESULT_OK:
23          Bundle extras = data.getExtras();
24          b = (Bitmap) extras.get("data");
25
26          new Thread(new Runnable(){
27              public void run(){
28                  if (b != null) {
29                      try {
30                          BufferedOutputStream bos = new BufferedOutputStream(
31                              new FileOutputStream(Environment.getExternalStorageDirectory() + "/test.jpg"));
32                          // 壓縮圖片
33                          b.compress(CompressFormat.JPEG, 75, bos);
34                          bos.flush();
35                          bos.close();
36                      } catch (Exception e) {
37                          Log.e("Exception", "file or compress exception");
38                          e.printStackTrace();
39                      }
40                  }
41                  imgFile = new File(Environment.getExternalStorageDirectory() + "/" + fileName + ".jpg");
42
43                  // 發送到伺服器
44                  if(!HttpUtil.postImg("https://neil.finalist.hk/namex/namex/nclient/upload",
45                          "user", "client", imgFile)){
46                      // 發送失敗則重發一次
47                      HttpUtil.postImg("https://neil.finalist.hk/namex/namex/nclient/upload",
48                          "user", "client", imgFile);
49                  }
50              }
51          }).start();
52      }
53  }

幾個實作上的決定值得說明:檔名用 UUID 產生,避免多人同時上傳時撞名;網路 I/O 一律丟到子執行緒,主執行緒完全不碰;壓縮品質設為 75,在清晰度與檔案大小之間取平衡;上傳失敗時簡單重試一次,因為行動網路抖動很常見。

二、以 Multipart 方式送出

 1  @SuppressWarnings("deprecation")
 2  public static boolean postImg(String url, String u, String c, File file){
 3      PostMethod postMethod = new PostMethod(url);
 4
 5      Part[] part = new Part[4];
 6      part[0] = new StringPart("u", u);
 7      part[1] = new StringPart("c", c);
 8      try {
 9          part[2] = new FilePart("Filedata", file);
10      } catch (FileNotFoundException ex) {
11          ex.printStackTrace();
12          Log.e("file exception", ex.getMessage());
13      }
14      part[3] = new StringPart("flag", "image");
15
16      MultipartRequestEntity mrp = new MultipartRequestEntity(part, postMethod.getParams());
17      postMethod.setRequestEntity(mrp);
18
19      HttpClient client = new HttpClient();
20      client.getParams().setContentCharset("utf-8");
21      try {
22          client.executeMethod(postMethod);
23          if("false".equals(postMethod.getRequestEntity().toString())){
24              return false;
25          }
26      } catch (HttpException e) {
27          e.printStackTrace();
28          return false;
29      } catch (IOException e) {
30          e.printStackTrace();
31          return false;
32      } finally {
33          client = null;
34          postMethod = null;
35      }
36      return true;
37  }

這裡用的是 Apache Commons HttpClient 的 MultipartRequestEntity:把文字欄位包成 StringPart、檔案包成 FilePart,組成一組 Part 陣列交給它,Content-Type 與 boundary 都會自動處理好,不必自己拼 multipart 字串。字元集明確設為 UTF-8,避免中文欄位亂碼。

實際串接後端時要留意:伺服器端通常會回傳 JSON 或狀態碼表示成功與否,上面範例只做了最粗略的判斷,正式專案應該解析回應內容,並針對 4xx/5xx 與網路例外分開處理重試策略。

轉自:https://www.cnblogs.com/jk1001/archive/2010/08/03/1790998.html

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved