国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Golang+Android基于HttpURLConnection實現的文件上傳功能示例

2019-12-12 03:32:08
字體:
來源:轉載
供稿:網友

本文實例講述了Golang+Android基于HttpURLConnection實現的文件上傳功能。分享給大家供大家參考,具體如下:

這里要演示的是使用Android程序作為客戶端(使用HttpURLConnection訪問網絡),Golang程序作為服務器端,實現文件上傳。

客戶端代碼:

public static String uploadFile(String uploadUrl, String filePath) {    Log.v(TAG, "url:" + uploadUrl);    Log.v(TAG, "filePath:" + filePath);    String nextLine = "/r/n";    String dividerStart = "--";    String boundary = "******";    try {      URL url = new URL(uploadUrl);      HttpURLConnection connection = (HttpURLConnection) url.openConnection();      connection.setChunkedStreamingMode(1024 * 256);      connection.setDoInput(true);      connection.setDoOutput(true);      connection.setUseCaches(false);      connection.setRequestMethod("POST");      // 設置Http請求頭      connection.setRequestProperty("Connection", "Keep-Alive");      connection.setRequestProperty("Charset", "UTF-8");      //必須在Content-Type 請求頭中指定分界符      connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);      //定義數據寫入流,準備上傳文件      DataOutputStream dos = new DataOutputStream(connection.getOutputStream());      dos.writeBytes(dividerStart + boundary + nextLine);      //設置與上傳文件相關的信息      dos.writeBytes("Content-Disposition: form-data; name=/"file/"; filename=/""          + filePath.substring(filePath.lastIndexOf("/") + 1) + "/"" + nextLine);      dos.writeBytes(nextLine);      FileInputStream fis = new FileInputStream(filePath);      byte[] buffer = new byte[1024 * 32];      int count;      // 讀取文件內容,并寫入OutputStream對象      while ((count = fis.read(buffer)) != -1) {        dos.write(buffer, 0, count);      }      fis.close();      dos.writeBytes(nextLine);      dos.writeBytes(dividerStart + boundary + dividerStart + nextLine);      dos.flush();      // 開始讀取從服務器傳過來的信息      InputStream is = connection.getInputStream();      BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));      String result = br.readLine();      dos.close();      is.close();      connection.disconnect();      return result;    } catch (IOException e) {      e.printStackTrace();    }    return null;}

服務器端代碼:

復制代碼 代碼如下:
package webserver
//接收客戶端通過http上傳的文件
//Date: 2015-3-25 16:18:33
import (
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
    "os"
)
func UpLoadBase() {
    fmt.Println("This is uploadbase")
    http.HandleFunc("/httpUploadFile", handleUploadFile)
    http.ListenAndServe(":8086", nil)
    if err != nil {
        fmt.Println("ListenAndServe error: ", err.Error())
    }
}
func handleUploadFile(w http.ResponseWriter, r *http.Request) {
    fmt.Println("client:", r.RemoteAddr)
    file, fileHeader, err := r.FormFile("file")
    if err != nil {
        log.Fatal("FormFile:", err.Error())
        return
    }
    defer func() {
        if err := file.Close(); err != nil {
            log.Fatal("Close:", err.Error())
            return
        }
    }()
    //文件名
    fileName := fileHeader.Filename
    if fileName == "" {
        log.Fatal("Param filename cannot be null.")
        return
    }
    //文件內容
    bytes, err := ioutil.ReadAll(file)
    //寫到服務端本地文件中
    outputFilePath := "/home/admin/桌面/" + fileName
    err = ioutil.WriteFile(outputFilePath, bytes, os.ModePerm)
    if err != nil {
        log.Fatal("WriteFileError:", err.Error())
        return
    }
    w.Write(([]byte)("上傳文件成功!"))
}

更多關于Android相關內容感興趣的讀者可查看本站專題:《Android開發入門與進階教程》、《Android調試技巧與常見問題解決方法匯總》、《Android基本組件用法總結》、《Android視圖View技巧總結》、《Android布局layout技巧總結》及《Android控件用法總結

希望本文所述對大家Android程序設計有所幫助。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 彰化县| 额尔古纳市| 大丰市| 尖扎县| 凌云县| 广灵县| 长岭县| 湖南省| 徐汇区| 大邑县| 萝北县| 文登市| 泸西县| 宜君县| 大关县| 乐平市| 三门县| 汤原县| 玛纳斯县| 林芝县| 汕头市| 阿坝县| 南澳县| 天祝| 汝州市| 抚宁县| 涡阳县| 建水县| 乐东| 施甸县| 陇南市| 子洲县| 秦皇岛市| 重庆市| 麻江县| 冷水江市| 墨江| 新巴尔虎右旗| 湘西| 新绛县| 乌拉特中旗|