Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

以 Android Http 實作檔案的上傳與下載完整教學

編輯:關於 Android 程式設計

近期參與的一個專案需要處理檔案的上傳與下載,這類功能網路上到處都能找到範例。於是我便從網路收集了一批程式碼直接使用,沒想到品質參差不齊:有的寫得不够完整,有的乾脆跑不起來。折騰一番後,我索性自己重新整理了一份可用且較為周全的實作,特別記錄下來,希望能幫到更多正在為此煩惱的朋友。

檔案上傳

這裡透過 org.apache.commons.httpclient.HttpClient 來完成檔案上傳,對應的 jar 套件可以直接上網搜尋並下載。

 /** * @param mContext 上下文 * @param targetUrl 文件上傳地址 * @param filePath 文件路徑 */ public void uploadFile(final Activity mContext, String targetUrl, final String filePath) { System.out.println("targetUrl: " + targetUrl + " filePath: " + filePath); if (TextUtils.isEmpty(filePath)) { Toast.makeText(mContext, "文件不存在", Toast.LENGTH_SHORT).show(); return; } final PostMethod filePost = new PostMethod(targetUrl) {//這個用來中文亂碼 public String getRequestCharSet() { return "UTF-8"; } }; try { final HttpClient client = new HttpClient(); File file = new File(filePath); if (file.exists() && file.isFile()) { long fileSize = file.length(); if (fileSize >= 5 * 1024 * 1024) { Toast.makeText(mContext, "文件不得大於5M", Toast.LENGTH_SHORT).show(); return; } } else { Toast.makeText(mContext, "文件不存在", Toast.LENGTH_SHORT).show(); return; } // 上傳文件和參數 Part[] parts = new Part[]{new CustomFilePart(file.getName(), file), new StringPart("filename", file.getName(), "UTF-8")}; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); new Thread(new Runnable() { @Override public void run() { int statuscode = 0; try { statuscode = client.executeMethod(filePost); } catch (IOException e) { e.printStackTrace(); } final int finalStatuscode = statuscode; mContext.runOnUiThread(new Runnable() { @Override public void run() { if (finalStatuscode == HttpStatus.SC_OK) { Toast.makeText(mContext, "上傳成功", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(mContext, "上傳失敗", Toast.LENGTH_SHORT).show(); } } }); } }).start(); } catch (Exception ex) { ex.printStackTrace(); } } 

使用 HttpClient 時經常會碰到中文亂碼,通常要從兩個環節著手處理。第一是重寫 PostMethod 的 getRequestCharSet 方法,明確指定請求編碼:

 final PostMethod filePost = new PostMethod(targetUrl) {//這個用來中文亂碼 public String getRequestCharSet() { return "UTF-8"; } };

第二則是自行定義 FilePart,為請求參數指定編碼,特別是處理含中文的檔名時:

 /** * 解決中文文件名亂碼 */ public class CustomFilePart extends FilePart { public CustomFilePart(String filename, File file) throws FileNotFoundException { super(filename, file); } protected void sendDispositionHeader(OutputStream out) throws IOException { super.sendDispositionHeader(out); String filename = getSource().getFileName(); if (filename != null) { out.write(EncodingUtil.getAsciiBytes(FILE_NAME)); out.write(QUOTE_BYTES); out.write(EncodingUtil.getBytes(filename, "UTF-8")); out.write(QUOTE_BYTES); } } }

接著用自訂的 CustomFilePart 來組裝參數:

 Part[] parts = new Part[]{new CustomFilePart(file.getName(), file), new StringPart("filename", file.getName(), "UTF-8")}; filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

檔案下載

下載則改以 HttpURLConnection 實作。

 /** * @param urlStr 文件地址 * @param path 文件保存路徑 * @param fileName 文件名 * @return 文件的絕對路徑 */ public String downFile(String urlStr, String path, String fileName) { InputStream inputStream = null; String filePath = null; try { FileUtils fileUtils = new FileUtils(); //判斷文件是否存在 if (fileUtils.isFileExist(path + fileName)) { System.out.println("exits"); filePath = SDPATH + path + fileName; } else { //得到io流 inputStream = getInputStreamFromURL(urlStr); //從input流中將文件寫入SD卡中 File resultFile = fileUtils.write2SDFromInput(path, fileName, inputStream); if (resultFile != null) { filePath = resultFile.getPath(); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (inputStream != null) inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return filePath; } /** * 根據URL得到輸入流 * * @param urlStr * @return */ public InputStream getInputStreamFromURL(String urlStr) { HttpURLConnection urlConn; InputStream inputStream = null; try { url = new URL(urlStr); urlConn = (HttpURLConnection) url.openConnection(); inputStream = urlConn.getInputStream(); } catch (Exception e) { e.printStackTrace(); } return inputStream; }

說穿了,下載的本質並不複雜:透過 HTTP 取得 InputStream,再解析這個串流並寫入檔案即可。以下示範如何把串流讀出並落盤到 SD 卡。

 /** * 將一個InputStream裡面的數據寫入到SD卡中 * * @param path 文件保存路徑 * @param fileName 文件保存的名字 * @param input 文件輸入流 * @return 文件 */ public File write2SDFromInput(String path, String fileName, InputStream input) { File file = null; OutputStream output = null; try { // 創建文件夾 createSDDir(path); // 創建文件 file = createSDFile(path + fileName); // 開啟輸出流,准備寫入文件 output = new FileOutputStream(file); // 緩沖區 byte[] buffer = new byte[FILESIZE]; int count; while ((count = input.read(buffer)) != -1) { // 這裡,請一定按該方式寫入文件,不然時而會出現文件寫入錯誤,數據丟失問題 output.write(buffer, 0, count); } output.flush(); } catch (Exception e) { e.printStackTrace(); } finally { try { output.close(); input.close(); } catch (IOException e) { e.printStackTrace(); } } return file; }

把串流寫入 SD 卡時有個關鍵細節,值得留意 OutputStream 的 write 方法。我建議使用帶三個參數的 write(byte[] b, int off, int len) 版本,這樣能有效避免資料遺失的問題。寫入時請務必採用下面的寫法:

 while ((count = input.read(buffer)) != -1) { // 這裡,請一定按該方式寫入文件,不然時而會出現文件寫入錯誤,數據丟失問題 output.write(buffer, 0, count); }

完整原始碼可參考:https://github.com/zuiwuyuan/Http_Uploader_Downloader

以上便是整理的 Android Http 檔案上傳與下載實作,希望能對有需要的開發者有所幫助。

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