Android中如何使用HttpURLConnection實(shí)現(xiàn)一個(gè)文件上傳

今天就跟大家聊聊有關(guān)Android中如何使用HttpURLConnection實(shí)現(xiàn)一個(gè)文件上傳,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

成都創(chuàng)新互聯(lián)公司長(zhǎng)期為上千家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺(tái),與合作伙伴共同營(yíng)造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為成安企業(yè)提供專業(yè)的成都做網(wǎng)站、成都網(wǎng)站建設(shè)、成都外貿(mào)網(wǎng)站建設(shè),成安網(wǎng)站改版等技術(shù)服務(wù)。擁有10多年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。

客戶端代碼:

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");
      // 設(shè)置Http請(qǐng)求頭
      connection.setRequestProperty("Connection", "Keep-Alive");
      connection.setRequestProperty("Charset", "UTF-8");
      //必須在Content-Type 請(qǐng)求頭中指定分界符
      connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
      //定義數(shù)據(jù)寫入流,準(zhǔn)備上傳文件
      DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
      dos.writeBytes(dividerStart + boundary + nextLine);
      //設(shè)置與上傳文件相關(guān)的信息
      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;
      // 讀取文件內(nèi)容,并寫入OutputStream對(duì)象
      while ((count = fis.read(buffer)) != -1) {
        dos.write(buffer, 0, count);
      }
      fis.close();
      dos.writeBytes(nextLine);
      dos.writeBytes(dividerStart + boundary + dividerStart + nextLine);
      dos.flush();
      // 開始讀取從服務(wù)器傳過來(lái)的信息
      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;
}

服務(wù)器端代碼:

復(fù)制代碼 代碼如下:
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
    }
    //文件內(nèi)容
    bytes, err := ioutil.ReadAll(file)
    //寫到服務(wù)端本地文件中
    outputFilePath := "/home/admin/桌面/" + fileName
    err = ioutil.WriteFile(outputFilePath, bytes, os.ModePerm)
    if err != nil {
        log.Fatal("WriteFileError:", err.Error())
        return
    }
    w.Write(([]byte)("上傳文件成功!"))
}

看完上述內(nèi)容,你們對(duì)Android中如何使用HttpURLConnection實(shí)現(xiàn)一個(gè)文件上傳有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。

本文標(biāo)題:Android中如何使用HttpURLConnection實(shí)現(xiàn)一個(gè)文件上傳
文章鏈接:http://muchs.cn/article34/pdgepe.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計(jì)公司、網(wǎng)站制作網(wǎng)站改版、電子商務(wù)、云服務(wù)器、微信公眾號(hào)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

微信小程序開發(fā)