go post 上传文件的例子
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)
}
}
go post 上传文件的例子的更多相关文章
- 以一个上传文件的例子来说 DistributedFileSystem
public class UploadAndDown { public static void main(String[] args) { UploadAndDown uploadAndDown = ...
- PHP socket上传文件图片
最近了解了下下socket方面的东西,想做一个socket上传文件的例子. 在网上搜了搜代码执行后,图片数据传输了一半,图片的下半部分是灰色的.然后就自己仿着搜来的代码和php.net 中socket ...
- Javaweb向服务器上传文件以及从服务器下载文件的方法
先导入jar包 点击下载 commons-fileupload是Apache开发的一款专门用来处理上传的工具,它的作用就是可以从request对象中解析出,用户发送的请求参数和上传文件的流. comm ...
- WebUploader分片断点上传文件(二)
写在前面: 这几天,有去研究一下WebUploader上传文件,前面的博客有记录下使用WebUploader简单上传文件的例子,今天就把分片断点上传的例子也记录下吧,在博客园中,也查看了一些资料,基本 ...
- 关于PHP上传文件时配置 php.ini 中的 upload_tmp_dir
在<PHP 5.3 入门经典>9.6.3 的试一试中(P235),给出了一个上传文件的例子,这里的文件格式为jpeg图片(image/jpeg).如果之前未配置 php.ini 中的 up ...
- php使用curl 实现GET和POST请求(抓取网页,上传文件),支持跨项目和跨服务器
一:curl 函数和参数详解 函数库:1:curl_init 初始化一个curl会话2:curl_close 关闭一个curl会话3:curl_setopt 为一个curl设置会话参数4:curl_e ...
- 阿里云OSS 上传文件SDK
Aliyun OSS SDK for C# 上传文件 另外:查找的其他实现C#上传文件功能例子: 1.WPF用流的方式上传/显示/下载图片文件(保存在数据库) (文末有案例下载链接) 2.WPF中利用 ...
- Java使用HttpURLConnection上传文件(转)
从普通Web页面上传文件很简单,只需要在form标签叫上enctype="multipart/form-data"即可,剩余工作便都交给浏览器去完成数据收集并发送Http请求.但是 ...
- spring mvc(注解)上传文件的简单例子
spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...
随机推荐
- django之创建第6-2个项目-过滤器列表
转载:http://www.lidongkui.com/django-template-filter-table 一.转化为小写 {{ name | lower }} 二.串联:先转义文本到HTML, ...
- java正则表达式去除html中所有的标签和特殊HTML字符(以&开头的)
来源于:https://www.androiddev.net/java%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E5%8E%BB%E9%99%A4ht ...
- MySQL-join的实现原理、优化及NLJ算法
案例分析: select c.* from hotel_info_original c left join hotel_info_collection h on c.hotel_type=h.hote ...
- WKWebView 使用及注意事项
iOS8之后,苹果推出了WebKit这个框架,用来替换原有的UIWebView,新的控件优点多多.由于一直在适配iOS7,就没有去替换,现在仍掉了iOS7,以为很简单的就替换过来了,然而在替换的过程中 ...
- ipsec在企业网中的应用(IKE野蛮模式)(转)
from:http://lulu1101.blog.51cto.com/4455468/817954 ipsec在企业网中的应用(IKE野蛮模式) 案例: 本实验采用华为三台F100防火墙,和一台s3 ...
- 【虚拟化系列】VMware vSphere 5.1 网络管理
网络是VMware vSphere 5.1的基础,所有虚拟机都需要网络来进行通信.如果将所有的虚拟机都看成是物理机,则在网络拓扑上,需要网卡和交换机等不同的网络连接设备和方式.而在虚拟化中,这些 ...
- Nginx配置Awstats分析Nginx日志笔记
1.修改Nginx日志格式: log_format json '$remote_addr - $remote_user [$time_local] "$request" ' ...
- EF的表左连接方法Include和Join
在EF中表连接常用的有Join()和Include(),两者都可以实现两张表的连接,但又有所不同. 例如有个唱片表Album(AlbumId,Name,CreateDate,GenreId),表中含外 ...
- intellij idea 双击选中一个变量而不是单词
在keymap 里搜索 select Word at caret ,然后双击并在弹出选项里选add mouse shortcut,然后选double click,再在下面click pad 区域点一下 ...
- 【C语言】练习3-3
题目来源:<The C programming language>中的习题P49 练习2-9: 编写函数expand(s1, s2),将字符串s1中类似于a-z一类的速记符号在字符串s ...