閱讀104 返回首頁    go 阿裏雲 go 技術社區[雲棲]


android選擇圖片或拍照圖片上傳到服務器(包括上傳參數)

https://blog.csdn.net/vipa1888/article/details/8213898

最近要搞一個項目,需要上傳相冊和拍照的圖片,不負所望,終於完成了!  不過需要說明一下,其實網上很多教程拍照的圖片,都是縮略圖不是很清晰,所以需要在調用照相機的時候,事先生成一個地址,用於標識拍照的圖片URI

具體上傳代碼:

1.選擇圖片和上傳界麵,包括上傳完成和異常的回調監聽

[java] view plaincopy
  1. package com.spring.sky.image.upload;  
  2.   
  3.   
  4. import java.util.HashMap;  
  5. import java.util.Map;  
  6.   
  7. import android.app.Activity;  
  8. import android.app.ProgressDialog;  
  9. import android.content.Intent;  
  10. import android.graphics.Bitmap;  
  11. import android.graphics.BitmapFactory;  
  12. import android.os.Bundle;  
  13. import android.os.Handler;  
  14. import android.os.Message;  
  15. import android.util.Log;  
  16. import android.view.View;  
  17. import android.view.View.OnClickListener;  
  18. import android.widget.Button;  
  19. import android.widget.ImageView;  
  20. import android.widget.ProgressBar;  
  21. import android.widget.TextView;  
  22. import android.widget.Toast;  
  23.   
  24. import com.spring.sky.image.upload.network.UploadUtil;  
  25. import com.spring.sky.image.upload.network.UploadUtil.OnUploadProcessListener;  
  26. /** 
  27.  * @author spring sky<br> 
  28.  * Email :vipa1888@163.com<br> 
  29.  * QQ: 840950105<br> 
  30.  * 說明:主要用於選擇文件和上傳文件操作 
  31.  */  
  32. public class MainActivity extends Activity implements OnClickListener,OnUploadProcessListener{  
  33.     private static final String TAG = "uploadImage";  
  34.       
  35.     /** 
  36.      * 去上傳文件 
  37.      */  
  38.     protected static final int TO_UPLOAD_FILE = 1;    
  39.     /** 
  40.      * 上傳文件響應 
  41.      */  
  42.     protected static final int UPLOAD_FILE_DONE = 2;  //  
  43.     /** 
  44.      * 選擇文件 
  45.      */  
  46.     public static final int TO_SELECT_PHOTO = 3;  
  47.     /** 
  48.      * 上傳初始化 
  49.      */  
  50.     private static final int UPLOAD_INIT_PROCESS = 4;  
  51.     /** 
  52.      * 上傳中 
  53.      */  
  54.     private static final int UPLOAD_IN_PROCESS = 5;  
  55.     /*** 
  56.      * 這裏的這個URL是我服務器的javaEE環境URL 
  57.      */  
  58.     private static String requestURL = "https://192.168.10.160:8080/fileUpload/p/file!upload";  
  59.     private Button selectButton,uploadButton;  
  60.     private ImageView imageView;  
  61.     private TextView uploadImageResult;  
  62.     private ProgressBar progressBar;  
  63.       
  64.     private String picPath = null;  
  65.     private ProgressDialog progressDialog;  
  66.       
  67.     /** Called when the activity is first created. */  
  68.     @Override  
  69.     public void onCreate(Bundle savedInstanceState) {  
  70.         super.onCreate(savedInstanceState);  
  71.         setContentView(R.layout.main);  
  72.         initView();  
  73.     }  
  74.       
  75.     /** 
  76.      * 初始化數據 
  77.      */  
  78.     private void initView() {  
  79.         selectButton = (Button) this.findViewById(R.id.selectImage);  
  80.         uploadButton = (Button) this.findViewById(R.id.uploadImage);  
  81.         selectButton.setOnClickListener(this);  
  82.         uploadButton.setOnClickListener(this);  
  83.         imageView = (ImageView) this.findViewById(R.id.imageView);  
  84.         uploadImageResult = (TextView) findViewById(R.id.uploadImageResult);  
  85.         progressDialog = new ProgressDialog(this);  
  86.         progressBar = (ProgressBar) findViewById(R.id.progressBar1);  
  87.     }  
  88.   
  89.     @Override  
  90.     public void onClick(View v) {  
  91.         switch (v.getId()) {  
  92.         case R.id.selectImage:  
  93.             Intent intent = new Intent(this,SelectPicActivity.class);  
  94.             startActivityForResult(intent, TO_SELECT_PHOTO);  
  95.             break;  
  96.         case R.id.uploadImage:  
  97.             if(picPath!=null)  
  98.             {  
  99.                 handler.sendEmptyMessage(TO_UPLOAD_FILE);  
  100.             }else{  
  101.                 Toast.makeText(this"上傳的文件路徑出錯", Toast.LENGTH_LONG).show();  
  102.             }  
  103.             break;  
  104.         default:  
  105.             break;  
  106.         }  
  107.     }  
  108.   
  109.     @Override  
  110.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  111.         if(resultCode==Activity.RESULT_OK && requestCode == TO_SELECT_PHOTO)  
  112.         {  
  113.             picPath = data.getStringExtra(SelectPicActivity.KEY_PHOTO_PATH);  
  114.             Log.i(TAG, "最終選擇的圖片="+picPath);  
  115.             Bitmap bm = BitmapFactory.decodeFile(picPath);  
  116.             imageView.setImageBitmap(bm);  
  117.         }  
  118.         super.onActivityResult(requestCode, resultCode, data);  
  119.     }  
  120.       
  121.   
  122.     /** 
  123.      * 上傳服務器響應回調 
  124.      */  
  125.     @Override  
  126.     public void onUploadDone(int responseCode, String message) {  
  127.         progressDialog.dismiss();  
  128.         Message msg = Message.obtain();  
  129.         msg.what = UPLOAD_FILE_DONE;  
  130.         msg.arg1 = responseCode;  
  131.         msg.obj = message;  
  132.         handler.sendMessage(msg);  
  133.     }  
  134.       
  135.     private void toUploadFile()  
  136.     {  
  137.         uploadImageResult.setText("正在上傳中...");  
  138.         progressDialog.setMessage("正在上傳文件...");  
  139.         progressDialog.show();  
  140.         String fileKey = "pic";  
  141.         UploadUtil uploadUtil = UploadUtil.getInstance();;  
  142.         uploadUtil.setOnUploadProcessListener(this);  //設置監聽器監聽上傳狀態  
  143.           
  144.         Map<String, String> params = new HashMap<String, String>();  
  145.         params.put("orderId""11111");  
  146.         uploadUtil.uploadFile( picPath,fileKey, requestURL,params);  
  147.     }  
  148.       
  149.     private Handler handler = new Handler(){  
  150.         @Override  
  151.         public void handleMessage(Message msg) {  
  152.             switch (msg.what) {  
  153.             case TO_UPLOAD_FILE:  
  154.                 toUploadFile();  
  155.                 break;  
  156.               
  157.             case UPLOAD_INIT_PROCESS:  
  158.                 progressBar.setMax(msg.arg1);  
  159.                 break;  
  160.             case UPLOAD_IN_PROCESS:  
  161.                 progressBar.setProgress(msg.arg1);  
  162.                 break;  
  163.             case UPLOAD_FILE_DONE:  
  164.                 String result = "響應碼:"+msg.arg1+"\n響應信息:"+msg.obj+"\n耗時:"+UploadUtil.getRequestTime()+"秒";  
  165.                 uploadImageResult.setText(result);  
  166.                 break;  
  167.             default:  
  168.                 break;  
  169.             }  
  170.             super.handleMessage(msg);  
  171.         }  
  172.           
  173.     };  
  174.   
  175.     @Override  
  176.     public void onUploadProcess(int uploadSize) {  
  177.         Message msg = Message.obtain();  
  178.         msg.what = UPLOAD_IN_PROCESS;  
  179.         msg.arg1 = uploadSize;  
  180.         handler.sendMessage(msg );  
  181.     }  
  182.   
  183.     @Override  
  184.     public void initUpload(int fileSize) {  
  185.         Message msg = Message.obtain();  
  186.         msg.what = UPLOAD_INIT_PROCESS;  
  187.         msg.arg1 = fileSize;  
  188.         handler.sendMessage(msg );  
  189.     }  
  190.       
  191. }  


2.選擇圖片界麵,主要涉及兩種方式:選擇圖片和及時拍照圖片

[java] view plaincopy
  1. package com.spring.sky.image.upload;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.ContentValues;  
  5. import android.content.Intent;  
  6. import android.database.Cursor;  
  7. import android.net.Uri;  
  8. import android.os.Bundle;  
  9. import android.os.Environment;  
  10. import android.provider.MediaStore;  
  11. import android.util.Log;  
  12. import android.view.MotionEvent;  
  13. import android.view.View;  
  14. import android.view.View.OnClickListener;  
  15. import android.widget.Button;  
  16. import android.widget.LinearLayout;  
  17. import android.widget.Toast;  
  18.   
  19. /** 
  20.  * @author spring sky<br> 
  21.  * Email :vipa1888@163.com<br> 
  22.  * QQ: 840950105<br> 
  23.  * @version 創建時間:2012-11-22 上午9:20:03 
  24.  * 說明:主要用於選擇文件操作 
  25.  */  
  26.   
  27. public class SelectPicActivity extends Activity implements OnClickListener{  
  28.   
  29.     /*** 
  30.      * 使用照相機拍照獲取圖片 
  31.      */  
  32.     public static final int SELECT_PIC_BY_TACK_PHOTO = 1;  
  33.     /*** 
  34.      * 使用相冊中的圖片 
  35.      */  
  36.     public static final int SELECT_PIC_BY_PICK_PHOTO = 2;  
  37.       
  38.     /*** 
  39.      * 從Intent獲取圖片路徑的KEY 
  40.      */  
  41.     public static final String KEY_PHOTO_PATH = "photo_path";  
  42.       
  43.     private static final String TAG = "SelectPicActivity";  
  44.       
  45.     private LinearLayout dialogLayout;  
  46.     private Button takePhotoBtn,pickPhotoBtn,cancelBtn;  
  47.   
  48.     /**獲取到的圖片路徑*/  
  49.     private String picPath;  
  50.       
  51.     private Intent lastIntent ;  
  52.       
  53.     private Uri photoUri;  
  54.     @Override  
  55.     protected void onCreate(Bundle savedInstanceState) {  
  56.         super.onCreate(savedInstanceState);  
  57.         setContentView(R.layout.select_pic_layout);  
  58.         initView();  
  59.     }  
  60.     /** 
  61.      * 初始化加載View 
  62.      */  
  63.     private void initView() {  
  64.         dialogLayout = (LinearLayout) findViewById(R.id.dialog_layout);  
  65.         dialogLayout.setOnClickListener(this);  
  66.         takePhotoBtn = (Button) findViewById(R.id.btn_take_photo);  
  67.         takePhotoBtn.setOnClickListener(this);  
  68.         pickPhotoBtn = (Button) findViewById(R.id.btn_pick_photo);  
  69.         pickPhotoBtn.setOnClickListener(this);  
  70.         cancelBtn = (Button) findViewById(R.id.btn_cancel);  
  71.         cancelBtn.setOnClickListener(this);  
  72.           
  73.         lastIntent = getIntent();  
  74.     }  
  75.   
  76.     @Override  
  77.     public void onClick(View v) {  
  78.         switch (v.getId()) {  
  79.         case R.id.dialog_layout:  
  80.             finish();  
  81.             break;  
  82.         case R.id.btn_take_photo:  
  83.             takePhoto();  
  84.             break;  
  85.         case R.id.btn_pick_photo:  
  86.             pickPhoto();  
  87.             break;  
  88.         default:  
  89.             finish();  
  90.             break;  
  91.         }  
  92.     }  
  93.   
  94.     /** 
  95.      * 拍照獲取圖片 
  96.      */  
  97.     private void takePhoto() {  
  98.         //執行拍照前,應該先判斷SD卡是否存在  
  99.         String SDState = Environment.getExternalStorageState();  
  100.         if(SDState.equals(Environment.MEDIA_MOUNTED))  
  101.         {  
  102.               
  103.             Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//"android.media.action.IMAGE_CAPTURE"  
  104.             /*** 
  105.              * 需要說明一下,以下操作使用照相機拍照,拍照後的圖片會存放在相冊中的 
  106.              * 這裏使用的這種方式有一個好處就是獲取的圖片是拍照後的原圖 
  107.              * 如果不實用ContentValues存放照片路徑的話,拍照後獲取的圖片為縮略圖不清晰 
  108.              */  
  109.             ContentValues values = new ContentValues();    
  110.             photoUri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);    
  111.             intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri);  
  112.             /**-----------------*/  
  113.             startActivityForResult(intent, SELECT_PIC_BY_TACK_PHOTO);  
  114.         }else{  
  115.             Toast.makeText(this,"內存卡不存在", Toast.LENGTH_LONG).show();  
  116.         }  
  117.     }  
  118.   
  119.     /*** 
  120.      * 從相冊中取圖片 
  121.      */  
  122.     private void pickPhoto() {  
  123.         Intent intent = new Intent();  
  124.         intent.setType("image/*");  
  125.         intent.setAction(Intent.ACTION_GET_CONTENT);  
  126.         startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);  
  127.     }  
  128.       
  129.     @Override  
  130.     public boolean onTouchEvent(MotionEvent event) {  
  131.         finish();  
  132.         return super.onTouchEvent(event);  
  133.     }  
  134.       
  135.       
  136.     @Override  
  137.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  138.         if(resultCode == Activity.RESULT_OK)  
  139.         {  
  140.             doPhoto(requestCode,data);  
  141.         }  
  142.         super.onActivityResult(requestCode, resultCode, data);  
  143.     }  
  144.       
  145.     /**  
  146.      * 選擇圖片後,獲取圖片的路徑  
  147.      * @param requestCode  
  148.      * @param data  
  149.      */  
  150.     private void doPhoto(int requestCode,Intent data)  
  151.     {  
  152.         if(requestCode == SELECT_PIC_BY_PICK_PHOTO )  //從相冊取圖片,有些手機有異常情況,請注意  
  153.         {  
  154.             if(data == null)  
  155.             {  
  156.                 Toast.makeText(this"選擇圖片文件出錯", Toast.LENGTH_LONG).show();  
  157.                 return;  
  158.             }  
  159.             photoUri = data.getData();  
  160.             if(photoUri == null )  
  161.             {  
  162.                 Toast.makeText(this"選擇圖片文件出錯", Toast.LENGTH_LONG).show();  
  163.                 return;  
  164.             }  
  165.         }  
  166.         String[] pojo = {MediaStore.Images.Media.DATA};  
  167.         Cursor cursor = managedQuery(photoUri, pojo, nullnull,null);     
  168.         if(cursor != null )  
  169.         {  
  170.             int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);  
  171.             cursor.moveToFirst();  
  172.             picPath = cursor.getString(columnIndex);  
  173.             cursor.close();  
  174.         }  
  175.         Log.i(TAG, "imagePath = "+picPath);  
  176.         if(picPath != null && ( picPath.endsWith(".png") || picPath.endsWith(".PNG") ||picPath.endsWith(".jpg") ||picPath.endsWith(".JPG")  ))  
  177.         {  
  178.             lastIntent.putExtra(KEY_PHOTO_PATH, picPath);  
  179.             setResult(Activity.RESULT_OK, lastIntent);  
  180.             finish();  
  181.         }else{  
  182.             Toast.makeText(this"選擇圖片文件不正確", Toast.LENGTH_LONG).show();  
  183.         }  
  184.     }  
  185. }  


3. 上傳工具類,主要實現了圖片的上傳,上傳過程的初始化監聽和上傳完成的監聽,還有上傳耗時的計算

[java] view plaincopy
  1. package com.spring.sky.image.upload.network;  
  2.   
  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.net.HttpURLConnection;  
  9. import java.net.MalformedURLException;  
  10. import java.net.URL;  
  11. import java.util.Iterator;  
  12. import java.util.Map;  
  13. import java.util.UUID;  
  14.   
  15. import android.util.Log;  
  16.   
  17. /** 
  18.  *  
  19.  * 上傳工具類 
  20.  * @author spring sky<br> 
  21.  * Email :vipa1888@163.com<br> 
  22.  * QQ: 840950105<br> 
  23.  * 支持上傳文件和參數 
  24.  */  
  25. public class UploadUtil {  
  26.     private static UploadUtil uploadUtil;  
  27.     private static final String BOUNDARY =  UUID.randomUUID().toString(); // 邊界標識 隨機生成  
  28.     private static final String PREFIX = "--";  
  29.     private static final String LINE_END = "\r\n";  
  30.     private static final String CONTENT_TYPE = "multipart/form-data"// 內容類型  
  31.     private UploadUtil() {  
  32.   
  33.     }  
  34.   
  35.     /** 
  36.      * 單例模式獲取上傳工具類 
  37.      * @return 
  38.      */  
  39.     public static UploadUtil getInstance() {  
  40.         if (null == uploadUtil) {  
  41.             uploadUtil = new UploadUtil();  
  42.         }  
  43.         return uploadUtil;  
  44.     }  
  45.   
  46.     private static final String TAG = "UploadUtil";  
  47.     private int readTimeOut = 10 * 1000// 讀取超時  
  48.     private int connectTimeout = 10 * 1000// 超時時間  
  49.     /*** 
  50.      * 請求使用多長時間 
  51.      */  
  52.     private static int requestTime = 0;  
  53.       
  54.     private static final String CHARSET = "utf-8"// 設置編碼  
  55.   
  56.     /*** 
  57.      * 上傳成功 
  58.      */  
  59.     public static final int UPLOAD_SUCCESS_CODE = 1;  
  60.     /** 
  61.      * 文件不存在 
  62.      */  
  63.     public static final int UPLOAD_FILE_NOT_EXISTS_CODE = 2;  
  64.     /** 
  65.      * 服務器出錯 
  66.      */  
  67.     public static final int UPLOAD_SERVER_ERROR_CODE = 3;  
  68.     protected static final int WHAT_TO_UPLOAD = 1;  
  69.     protected static final int WHAT_UPLOAD_DONE = 2;  
  70.       
  71.     /** 
  72.      * android上傳文件到服務器 
  73.      *  
  74.      * @param filePath 
  75.      *            需要上傳的文件的路徑 
  76.      * @param fileKey 
  77.      *            在網頁上<input type=file name=xxx/> xxx就是這裏的fileKey 
  78.      * @param RequestURL 
  79.      *            請求的URL 
  80.      */  
  81.     public void uploadFile(String filePath, String fileKey, String RequestURL,  
  82.             Map<String, String> param) {  
  83.         if (filePath == null) {  
  84.             sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");  
  85.             return;  
  86.         }  
  87.         try {  
  88.             File file = new File(filePath);  
  89.             uploadFile(file, fileKey, RequestURL, param);  
  90.         } catch (Exception e) {  
  91.             sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");  
  92.             e.printStackTrace();  
  93.             return;  
  94.         }  
  95.     }  
  96.   
  97.     /** 
  98.      * android上傳文件到服務器 
  99.      *  
  100.      * @param file 
  101.      *            需要上傳的文件 
  102.      * @param fileKey 
  103.      *            在網頁上<input type=file name=xxx/> xxx就是這裏的fileKey 
  104.      * @param RequestURL 
  105.      *            請求的URL 
  106.      */  
  107.     public void uploadFile(final File file, final String fileKey,  
  108.             final String RequestURL, final Map<String, String> param) {  
  109.         if (file == null || (!file.exists())) {  
  110.             sendMessage(UPLOAD_FILE_NOT_EXISTS_CODE,"文件不存在");  
  111.             return;  
  112.         }  
  113.   
  114.         Log.i(TAG, "請求的URL=" + RequestURL);  
  115.         Log.i(TAG, "請求的fileName=" + file.getName());  
  116.         Log.i(TAG, "請求的fileKey=" + fileKey);  
  117.         new Thread(new Runnable() {  //開啟線程上傳文件  
  118.             @Override  
  119.             public void run() {  
  120.                 toUploadFile(file, fileKey, RequestURL, param);  
  121.             }  
  122.         }).start();  
  123.           
  124.     }  
  125.   
  126.     private void toUploadFile(File file, String fileKey, String RequestURL,  
  127.             Map<String, String> param) {  
  128.         String result = null;  
  129.         requestTime= 0;  
  130.           
  131.         long requestTime = System.currentTimeMillis();  
  132.         long responseTime = 0;  
  133.   
  134.         try {  
  135.             URL url = new URL(RequestURL);  
  136.             HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  137.             conn.setReadTimeout(readTimeOut);  
  138.             conn.setConnectTimeout(connectTimeout);  
  139.             conn.setDoInput(true); // 允許輸入流  
  140.             conn.setDoOutput(true); // 允許輸出流  
  141.             conn.setUseCaches(false); // 不允許使用緩存  
  142.             conn.setRequestMethod("POST"); // 請求方式  
  143.             conn.setRequestProperty("Charset", CHARSET); // 設置編碼  
  144.             conn.setRequestProperty("connection""keep-alive");  
  145.             conn.setRequestProperty("user-agent""Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");  
  146.             conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);  
  147. //          conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");  
  148.               
  149.             /** 
  150.              * 當文件不為空,把文件包裝並且上傳 
  151.              */  
  152.             DataOutputStream dos = new DataOutputStream(conn.getOutputStream());  
  153.             StringBuffer sb = null;  
  154.             String params = "";  
  155.               
  156.             /*** 
  157.              * 以下是用於上傳參數 
  158.              */  
  159.             if (param != null && param.size() > 0) {  
  160.                 Iterator<String> it = param.keySet().iterator();  
  161.                 while (it.hasNext()) {  
  162.                     sb = null;  
  163.                     sb = new StringBuffer();  
  164.                     String key = it.next();  
  165.                     String value = param.get(key);  
  166.                     sb.append(PREFIX).append(BOUNDARY).append(LINE_END);  
  167.                     sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END);  
  168.                     sb.append(value).append(LINE_END);  
  169.                     params = sb.toString();  
  170.                     Log.i(TAG, key+"="+params+"##");  
  171.                     dos.write(params.getBytes());  
  172. //                  dos.flush();  
  173.                 }  
  174.             }  
  175.               
  176.             sb = null;  
  177.             params = null;  
  178.             sb = new StringBuffer();  
  179.             /** 
  180.              * 這裏重點注意: name裏麵的值為服務器端需要key 隻有這個key 才可以得到對應的文件 
  181.              * filename是文件的名字,包含後綴名的 比如:abc.png 
  182.              */  
  183.             sb.append(PREFIX).append(BOUNDARY).append(LINE_END);  
  184.             sb.append("Content-Disposition:form-data; name=\"" + fileKey  
  185.                     + "\"; filename=\"" + file.getName() + "\"" + LINE_END);  
  186.             sb.append("Content-Type:image/pjpeg" + LINE_END); // 這裏配置的Content-type很重要的 ,用於服務器端辨別文件的類型的  
  187.             sb.append(LINE_END);  
  188.             params = sb.toString();  
  189.             sb = null;  
  190.               
  191.             Log.i(TAG, file.getName()+"=" + params+"##");  
  192.             dos.write(params.getBytes());  
  193.             /**上傳文件*/  
  194.             InputStream is = new FileInputStream(file);  
  195.             onUploadProcessListener.initUpload((int)file.length());  
  196.             byte[] bytes = new byte[1024];  
  197.             int len = 0;  
  198.             int curLen = 0;  
  199.             while ((len = is.read(bytes)) != -1) {  
  200.                 curLen += len;  
  201.                 dos.write(bytes, 0, len);  
  202.                 onUploadProcessListener.onUploadProcess(curLen);  
  203.             }  
  204.             is.close();  
  205.               
  206.             dos.write(LINE_END.getBytes());  
  207.             byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();  
  208.             dos.write(end_data);  
  209.             dos.flush();  
  210. //            
  211. //          dos.write(tempOutputStream.toByteArray());  
  212.             /** 
  213.              * 獲取響應碼 200=成功 當響應成功,獲取響應的流 
  214.              */  
  215.             int res = conn.getResponseCode();  
  216.             responseTime = System.currentTimeMillis();  
  217.             this.requestTime = (int) ((responseTime-requestTime)/1000);  
  218.             Log.e(TAG, "response code:" + res);  
  219.             if (res == 200) {  
  220.                 Log.e(TAG, "request success");  
  221.                 InputStream input = conn.getInputStream();  
  222.                 StringBuffer sb1 = new StringBuffer();  
  223.                 int ss;  
  224.                 while ((ss = input.read()) != -1) {  
  225.                     sb1.append((char) ss);  
  226.                 }  
  227.                 result = sb1.toString();  
  228.                 Log.e(TAG, "result : " + result);  
  229.                 sendMessage(UPLOAD_SUCCESS_CODE, "上傳結果:"  
  230.                         + result);  
  231.                 return;  
  232.             } else {  
  233.                 Log.e(TAG, "request error");  
  234.                 sendMessage(UPLOAD_SERVER_ERROR_CODE,"上傳失敗:code=" + res);  
  235.                 return;  
  236.             }  
  237.         } catch (MalformedURLException e) {  
  238.             sendMessage(UPLOAD_SERVER_ERROR_CODE,"上傳失敗:error=" + e.getMessage());  
  239.             e.printStackTrace();  
  240.             return;  
  241.         } catch (IOException e) {  
  242.             sendMessage(UPLOAD_SERVER_ERROR_CODE,"上傳失敗:error=" + e.getMessage());  
  243.             e.printStackTrace();  
  244.             return;  
  245.         }  
  246.     }  
  247.   
  248.     /** 
  249.      * 發送上傳結果 
  250.      * @param responseCode 
  251.      * @param responseMessage 
  252.      */  
  253.     private void sendMessage(int responseCode,String responseMessage)  
  254.     {  
  255.         onUploadProcessListener.onUploadDone(responseCode, responseMessage);  
  256.     }  
  257.       
  258.     /** 
  259.      * 下麵是一個自定義的回調函數,用到回調上傳文件是否完成 
  260.      *  
  261.      * @author shimingzheng 
  262.      *  
  263.      */  
  264.     public static interface OnUploadProcessListener {  
  265.         /** 
  266.          * 上傳響應 
  267.          * @param responseCode 
  268.          * @param message 
  269.          */  
  270.         void onUploadDone(最後更新:2017-04-04 07:04:13

      上一篇:go 係統管理員必備的實用工具集結
      下一篇:go 優酷盜播引版權方圍攻 視頻大佬陷孤軍奮戰困局