天天看點

Android 檔案的上傳

使用 AsyncHttpClient來實作檔案的上傳功能

當然,這裡需要首先導入asyncHttpClient依賴的jar包

上傳檔案的基本操作步驟:

明确讀取檔案的路徑與上傳檔案的位址

依據檔案的路徑将上傳檔案封裝為File

依據上傳檔案的目标位址設定網絡請求的方式

進行檔案的上傳的操作

擷取檔案上傳的結果

//上傳檔案的路徑
	private String uploadLocaleUrl=""
	//上傳檔案的目的位址
	private String uploadServletUrl=""
	//點選按鈕 進行檔案上傳 
	public void click(View v) {
		
		//依據上傳檔案的路徑 建構file 對象
		File file = new File(uploadLocaleUrl);
		if (file.exists()&&file.length()>0) {
		//擷取asynchttpclient的執行個體 
		AsyncHttpClient client = new AsyncHttpClient();
		//進行檔案的上傳  發送一個post請求 
		 RequestParams params = new RequestParams();
		 try {
			params.put("profile_picture", file);// Upload a File
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} 
		
		client.post(uploadUrl, params, new AsyncHttpResponseHandler() {
			//上傳成功後 調用這個方法
			@Override
			public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
				Toast.makeText(getApplicationContext(), "上傳成功", 0).show();
				
			}
			
			@Override
			public void onProgress(int bytesWritten, int totalSize) {
				//設定進度條的總大小  
				pb_bar.setMax(totalSize);
				//設定進度條的目前進度
				pb_bar.setProgress(bytesWritten);
				
				super.onProgress(bytesWritten, totalSize);
			}
			//上傳失敗
			@Override
			public void onFailure(int statusCode, Header[] headers,
					byte[] responseBody, Throwable error) {
				
			}
		});
		
		}else {
			System.out.println("請檢測檔案對象 ...");
			
		}           

注意:需要添加連網的權限

使用 HttpURLConnection實作檔案的上傳

使用這種方法比較麻煩,封裝的參數比較多

//上傳檔案的位址路徑
    private String uploadServiletUrl = "";
    //上傳檔案的路徑
    private String uploadLocaleUrl = "";
    private void uploadFile()
    {
      String end = "/r/n";
      String Hyphens = "--";
      String boundary = "*****";
      File file = new File(uploadLocaleUrl);
      try
      {
        URL url = new URL(uploadServiletUrl);
        //建立一個連接配接
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        /* 允許Input、Output,不使用Cache */
        con.setDoInput(true);//允許輸入流
        con.setDoOutput(true);//允許輸出流
        con.setUseCaches(false);//設定不使用緩存
        //設定請求的方式為post
        con.setRequestMethod("POST");
        //設定請求的參數
        con.setRequestProperty("Connection", "Keep-Alive");
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
        //設定輸出流
        DataOutputStream ds = new DataOutputStream(con.getOutputStream());
        ds.writeBytes(Hyphens + boundary + end);
        ds.writeBytes("Content-Disposition: form-data; "+"name=/"+file+"/"+"newName/"+end);
        ds.writeBytes(end);
        /* 取得檔案的FileInputStream */
        FileInputStream fStream = new FileInputStream(uploadLocaleUrl);
        /* 設定每次寫入1024bytes */
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        int length = -1;
        /* 從檔案讀取資料到緩沖區 */
        while ((length = fStream.read(buffer)) != -1)
        {
          /* 将資料寫入DataOutputStream中 */
          ds.write(buffer, 0, length);
        }
        ds.writeBytes(end);
        ds.writeBytes(Hyphens + boundary + Hyphens + end);
        fStream.close();
        ds.flush();
        //擷取伺服器傳回的資料
        InputStream is = con.getInputStream();
        int ch;
        StringBuffer stringBuffer= new StringBuffer();
        while ((ch = is.read()) != -1)
        {
        	stringBuffer.append((char) ch);
        }
        System.out.println("上傳成功");;
        ds.close();
      } catch (Exception e)
      {
        System.out.println("上傳失敗" + e.getMessage());
      }
    }           

繼續閱讀