Golang+Android基于HttpURLConnection实现的文件上传功能示例
作者:books1958 时间:2023-10-27 06:19:46
本文实例讲述了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程序设计有所帮助。
标签:Golang,Android,文件上传
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java(TM) Platform SE binary 打开jar文件的操作
2021-10-02 00:08:12
![](https://img.aspxhome.com/file/2023/4/62534_0s.jpg)
SrpingDruid数据源加密数据库密码的示例代码
2021-06-21 03:26:26
![](https://img.aspxhome.com/file/2023/1/63021_0s.png)
Android实现本地上传图片并设置为圆形头像
2022-05-17 03:50:28
![](https://img.aspxhome.com/file/2023/3/92583_0s.png)
Spring Aop 如何获取参数名参数值
2022-09-08 17:00:41
详解Springboot自定义异常处理
2021-11-04 17:15:12
C#操作注册表之Registry类
2023-02-24 00:23:33
java微信公众号开发(搭建本地测试环境)
2021-07-07 05:32:40
![](https://img.aspxhome.com/file/2023/6/63076_0s.png)
Android开发中使用外部应用获取SD卡状态的方法
2023-02-01 21:03:45
官方详解HDFS Balancer工具主要调优参数
2023-07-24 04:43:47
Android App在线程中创建handler的方法讲解
2021-06-24 17:00:33
![](https://img.aspxhome.com/file/2023/2/138662_0s.png)
Android自定义控件绘制基本图形基础入门
2023-06-23 07:19:04
C#文件流读写和进度回调示例详解
2022-08-12 14:52:31
![](https://img.aspxhome.com/file/2023/6/79056_0s.jpg)
java实现的RSA加密算法详解
2022-11-19 06:14:44
C# using的本质及使用详解
2022-10-10 06:11:23
![](https://img.aspxhome.com/file/2023/0/76390_0s.png)
C# 分支与循环介绍
2022-10-26 13:50:02
常用json与javabean互转的方法实现
2023-01-07 14:24:19
![](https://img.aspxhome.com/file/2023/7/63737_0s.png)
详解java一维数组及练习题实例
2023-05-21 17:31:56
Android拼接实现动态对象方法详解
2021-12-23 10:09:46
![](https://img.aspxhome.com/file/2023/2/138002_0s.jpg)
springboot的yml配置文件通过db2的方式整合mysql的教程
2023-08-06 04:28:55
C# 基于udp广播收集局域网类所有设备信息
2022-04-28 00:17:23
![](https://img.aspxhome.com/file/2023/5/111215_0s.png)