Golang+Android基于HttpURLConnection实现的文件上传功能示例
程序员文章站
2024-02-11 17:53:28
本文实例讲述了golang+android基于httpurlconnection实现的文件上传功能。分享给大家供大家参考,具体如下:
这里要演示的是使用android程序...
本文实例讲述了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)("上传文件成功!"))
}
//接收客户端通过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程序设计有所帮助。