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 ...
随机推荐
- .Net(c#)加密解密工具类:
/// <summary> /// .Net加密解密帮助类 /// </summary> public class NetCryptoHelper { #region des实 ...
- Linux管道思想
1.Linux管道 {{book | upper |lower | capfirst}} 含义:就是把前一个命令的结果当成后一个命令的输入.然后在下一个管道中输出满足条件的数据,如此继续数据的流向运动 ...
- HP ALM
HP ALM 使用经验 使用HP ALM(Application Lifecycle Management)软件有一个多月的时间了,我是从安装,部署,建项,配置,使用,再到问题收集,这个过程过来的.发 ...
- 编译Boost库
VS版本: 虽然网络上有,但是还是记录下,找到VS的command prompt,然后切换到boost的根目录: 1.运行 bootstrap.bat 它在当前目录下会生成b2.exe2. 2.运行b ...
- Pinyin4j导读
Pinyin4j是Java中的拼音库,作者李民. 拼音这件事其实非常简单,无非是一种映射.但是拼音中包含的学问很多,很多前贤都研究过汉语拼音,提出了多种拼音方案.随着历史变迁,拼音的形式也在不断发生变 ...
- java struts2入门学习---文件下载的二种方式
一.关于文件下载: 文件下载的核心思想即是将文件从一个地方拷贝到另一个地方. 1.传统方式: 在Action中加入大量servlet api 操作.优点是好理解,缺点是耦合度高. 2.stream方式 ...
- memcached全面剖析--2.理解memcached的内存存储
下面是<memcached全面剖析>的第二部分. 发表日:2008/7/9 作者:前坂徹(Toru Maesaka) 原文链接:http://gihyo.jp/dev/feature/01 ...
- 【C#】C#项目如何获得项目的根目录
编写程序的时候,经常需要用的项目根目录.自己总结如下 1.取得控制台应用程序的根目录方法 方法1.Environment.CurrentDirectory 取得或设置当前工作目录的完整限定路径 ...
- codesmith连接postgresql修复bug
转:CodeSmith7代码生成器针对PostgreSQL数据库无法使用的Bug修复全过程 我自己又修改过,完整的PostgreSQLSchemaProvider.cs文件如下 using Npgsq ...
- is-a,has-a,like-a是什么 sql server中,N''表示什么意思? 关于SQL SERVER的N前缀的理解
https://blog.csdn.net/ooppookid/article/details/51174122#commentBox 1.is-a,has-a,like-a是什么 在面向对象设计的领 ...