Golang+Android基于HttpURLConnection實(shí)現(xiàn)的文件上傳功能示例
本文實(shí)例講述了Golang+Android基于HttpURLConnection實(shí)現(xiàn)的文件上傳功能。分享給大家供大家參考,具體如下:
這里要演示的是使用Android程序作為客戶端(使用HttpURLConnection訪問(wèn)網(wǎng)絡(luò)),Golang程序作為服務(wù)器端,實(shí)現(xiàn)文件上傳。
客戶端代碼:
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();
// 開(kāi)始讀取從服務(wù)器傳過(guò)來(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ù)器端代碼:
//接收客戶端通過(guò)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)("上傳文件成功!"))
}
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android開(kāi)發(fā)入門與進(jìn)階教程》、《Android調(diào)試技巧與常見(jiàn)問(wèn)題解決方法匯總》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對(duì)大家Android程序設(shè)計(jì)有所幫助。
相關(guān)文章
Android實(shí)現(xiàn)圖片在屏幕內(nèi)縮放和移動(dòng)效果
這篇文章主要為大家詳細(xì)介紹了Android控制圖片在屏幕內(nèi)縮放和移動(dòng)效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02
Flutter Navigator路由傳參的實(shí)現(xiàn)
本文主要介紹了Flutter Navigator路由傳參的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04
Android自定義Camera實(shí)現(xiàn)拍照功能
這篇文章主要為大家詳細(xì)介紹了Android自定義Camera實(shí)現(xiàn)拍照功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05
RecycleView實(shí)現(xiàn)各種尺寸圖片展示
這篇文章主要為大家詳細(xì)介紹了RecycleView實(shí)現(xiàn)各種尺寸圖片展示,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-05-05
Android RecyclerView詳解及簡(jiǎn)單實(shí)例
這篇文章主要介紹了Android RecyclerView詳解及簡(jiǎn)單實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-01-01
Android:利用SharedPreferences實(shí)現(xiàn)自動(dòng)登錄
本篇文章主要介紹了Android實(shí)現(xiàn)自動(dòng)登錄,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2016-11-11
android實(shí)現(xiàn)listview分頁(yè)的方法
這篇文章主要介紹了android實(shí)現(xiàn)listview分頁(yè)的方法,涉及Android生成listview列表的相關(guān)技巧,需要的朋友可以參考下2015-05-05
Android Flutter實(shí)戰(zhàn)之為照片添加顏色濾鏡
這篇文章我們將利用TweenAnimationBuilder來(lái)實(shí)現(xiàn)一個(gè)圖片調(diào)色的過(guò)渡動(dòng)畫,從而實(shí)現(xiàn)為照片添加顏色濾鏡的效果,感興趣的可以了解一下2022-12-12

