Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android 上傳文件到服務器代碼

android 上傳文件到服務器代碼

編輯:關於Android編程

代碼裡面已經注釋很清楚了~ 放這裡隨時拿來用的~ public class UploadUtil {

private static final String TAG = "TTTTTT upload";

private static final int TIME_OUT = 10 * 1000; // 超時時間

private static final String CHARSET = "utf-8"; // 設置編碼


public static String uploadFile(File file, String RequestURL) {

String result = null;

String BOUNDARY = UUID.randomUUID().toString(); // 邊界標識 隨機生成

String CONTENT_TYPE = "multipart/form-data"; // 內容類型


try {

URL url = new URL(RequestURL);

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setReadTimeout(TIME_OUT);

conn.setConnectTimeout(TIME_OUT);

conn.setDoInput(true); // 允許輸入流

conn.setDoOutput(true); // 允許輸出流

conn.setUseCaches(false); // 不允許使用緩存

conn.setRequestMethod("POST"); // 請求方式

conn.setRequestProperty("Charset", CHARSET); // 設置編碼

conn.setRequestProperty("connection", "keep-alive");

conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);


if (file != null) {

/**

* 當文件不為空,把文件包裝並且上傳

*/

DataOutputStream dos = newDataOutputStream(conn.getOutputStream());

InputStream is = new FileInputStream(file);

byte[] bytes = new byte[1024];

int len = 0;

while ((len = is.read(bytes)) != -1) {

dos.write(bytes, 0, len);

}

is.close();

dos.flush();

/**

* 獲取響應碼 200=成功 當響應成功,獲取響應的流

*/

int res = conn.getResponseCode();

Log.e(TAG, "response code:" + res);

if (res == 200) {

Log.e(TAG, "request success");

InputStream input = conn.getInputStream();

StringBuffer sb1 = new StringBuffer();

int ss;

while ((ss = input.read()) != -1) {

sb1.append((char) ss);

}

result = sb1.toString();

Log.e(TAG, "result : " + result);

}

}else{

Log.e(TAG, "file not found!");

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return result;

}

}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved