广告
返回顶部
首页 > 资讯 > 后端开发 > GO >Golang+Android基于HttpURLConnection实现的文件上传功能示例
  • 565
分享到

Golang+Android基于HttpURLConnection实现的文件上传功能示例

示例文件上传golangAndroid 2022-06-06 11:06:07 565人浏览 独家记忆
摘要

本文实例讲述了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)("上传文件成功!"))
}

更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》

希望本文所述对大家Android程序设计有所帮助。

您可能感兴趣的文章:Android使用URLConnection提交请求的实现Android HttpURLConnection.getResponseCode()错误解决方法Android 中HttpURLConnection与HttpClient使用的简单实例Android中HttpURLConnection与HttpClient的使用与封装Android中使用HttpURLConnection实现GET POST JSON数据与下载图片Android通过HttpURLConnection和HttpClient接口实现网络编程Android开发使用HttpURLConnection进行网络编程详解【附源码下载】android 网络编程之网络通信几种方式实例分享Android网络编程之UDP通信模型实例Android开发使用URLConnection进行网络编程详解


您可能感兴趣的文档:

--结束END--

本文标题: Golang+Android基于HttpURLConnection实现的文件上传功能示例

本文链接: https://www.lsjlt.com/news/28351.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作