go post 上传文件
package main

import (
"bytes"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
) func postFile(filename string, target_url string) (*http.Response, error) {
body_buf := bytes.NewBufferString("")
body_writer := multipart.NewWriter(body_buf) // use the body_writer to write the Part headers to the buffer
_, err := body_writer.CreateFormFile("userfile", filename)
if err != nil {
fmt.Println("error writing to buffer")
return nil, err
} // the file data will be the second part of the body
fh, err := os.Open(filename)
if err != nil {
fmt.Println("error opening file")
return nil, err
}
// need to know the boundary to properly close the part myself.
boundary := body_writer.Boundary()
//close_string := fmt.Sprintf("\r\n--%s--\r\n", boundary)
close_buf := bytes.NewBufferString(fmt.Sprintf("\r\n--%s--\r\n", boundary)) // use multi-reader to defer the reading of the file data until
// writing to the socket buffer.
request_reader := io.MultiReader(body_buf, fh, close_buf)
fi, err := fh.Stat()
if err != nil {
fmt.Printf("Error Stating file: %s", filename)
return nil, err
}
req, err := http.NewRequest("POST", target_url, request_reader)
if err != nil {
return nil, err
} // Set headers for multipart, and Content Length
req.Header.Add("Content-Type", "multipart/form-data; boundary="+boundary)
req.ContentLength = fi.Size() + int64(body_buf.Len()) + int64(close_buf.Len()) return http.DefaultClient.Do(req)
} // sample usage
func main() {
target_url := "http://localhost:8086/upload"
filename := "/Users/wei/Downloads/21dian_1.9_10"
postFile(filename, target_url)
}
参考文章 https://matt.aimonetti.net/posts/2013/07/01/golang-multipart-file-upload-example/ 25 package main import (
"bytes"
"fmt"
"log"
"mime/multipart"
"net/http"
) // Creates a new file upload http request with optional extra params
func newMultipartRequest(url string, params map[string]string) (*http.Request, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
for key, val := range params {
_ = writer.WriteField(key, val)
}
writer.Close()
return http.NewRequest("POST", url, body)
} func main() {
extraParams := map[string]string{
"title": "My Document",
"author": "zieckey",
"description": "A document with all the Go programming language secrets",
}
request, err := newMultipartRequest("http://127.0.0.1:8091/echo", extraParams)
if err != nil {
log.Fatal(err)
}
client := &http.Client{}
resp, err := client.Do(request)
if err != nil {
log.Fatal(err)
} else {
body := &bytes.Buffer{}
_, err := body.ReadFrom(resp.Body)
if err != nil {
log.Fatal(err)
}
resp.Body.Close()
fmt.Println(resp.StatusCode)
fmt.Println(resp.Header)
fmt.Println(body)
}
}
multipart 的例子 package main import (
"bytes"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
) // Creates a new file upload http request with optional extra params
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close() body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
if err != nil {
return nil, err
}
_, err = io.Copy(part, file) for key, val := range params {
_ = writer.WriteField(key, val)
}
err = writer.Close()
if err != nil {
return nil, err
} request, err := http.NewRequest("POST", uri, body)
request.Header.Add("Content-Type", writer.FormDataContentType())
return request, err
} func main() {
path, _ := os.Getwd()
path += "/test.pdf"
extraParams := map[string]string{
"title": "My Document",
"author": "Matt Aimonetti",
"description": "A document with all the Go programming language secrets",
}
request, err := newfileUploadRequest("http://localhost:8086/upload", extraParams, "userfile", "/Users/wei/Downloads/21dian_1.9_10")
if err != nil {
log.Fatal(err)
}
client := &http.Client{}
resp, err := client.Do(request)
if err != nil {
log.Fatal(err)
} else {
body := &bytes.Buffer{}
_, err := body.ReadFrom(resp.Body)
if err != nil {
log.Fatal(err)
}
resp.Body.Close()
fmt.Println(resp.StatusCode)
fmt.Println(resp.Header) fmt.Println(body)
}
}

upload服务端例子

阅读原文

 

最新文章

  1. 使用javascript获取服务器时间
  2. 关于flume配置加载(二)
  3. php self与static的区别
  4. Android NDK中的C++调试踩坑标记
  5. MVC,布局页面
  6. 【技术贴】解决Mysql启动服务报错1067 进程意外终止
  7. 阿里云如何添加多个网站 for Linux(绑定域名)
  8. qemu cow镜像分析
  9. 07-从零玩转JavaWeb-对象内存分析
  10. Spring消息之JMS.
  11. Tips_钉钉免登前端实现
  12. Hibernate学习(七)———— hibernate中查询方式详解
  13. 25 个常用的 Linux iptables 规则
  14. 记一次windows服务开发中遇到的问题
  15. 【codeforces 175D】 Plane of Tanks: Duel
  16. b1.关于em和px的关系
  17. Eclipse创建Spring项目 未完
  18. oracle数据库 ORA-01017的解决办法
  19. 如何快速找到某个研究领域的所有SCI期刊
  20. python3.5 自带的虚拟环境使用

热门文章

  1. 【FinancialKnowledge】商业银行业务知识
  2. jqPlot图表插件学习之阴阳烛图
  3. VTK三维点集轮廓凸包提取
  4. SpringCloud stream连接RabbitMQ收发信息
  5. python之获取微信服务器的ip地址
  6. kibana对logstash监控获取不到数据
  7. Windows2008|2003超出最大连接数
  8. awbeci—一个帮助你快速处理日常工作的网址收集网站
  9. ios中一级导航
  10. Junit 4.x 单元测试,参数化测试,套件测试 实例