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服务端例子

阅读原文

 

go post 上传文件的例子的更多相关文章

  1. 以一个上传文件的例子来说 DistributedFileSystem

    public class UploadAndDown { public static void main(String[] args) { UploadAndDown uploadAndDown = ...

  2. PHP socket上传文件图片

    最近了解了下下socket方面的东西,想做一个socket上传文件的例子. 在网上搜了搜代码执行后,图片数据传输了一半,图片的下半部分是灰色的.然后就自己仿着搜来的代码和php.net 中socket ...

  3. Javaweb向服务器上传文件以及从服务器下载文件的方法

    先导入jar包 点击下载 commons-fileupload是Apache开发的一款专门用来处理上传的工具,它的作用就是可以从request对象中解析出,用户发送的请求参数和上传文件的流. comm ...

  4. WebUploader分片断点上传文件(二)

    写在前面: 这几天,有去研究一下WebUploader上传文件,前面的博客有记录下使用WebUploader简单上传文件的例子,今天就把分片断点上传的例子也记录下吧,在博客园中,也查看了一些资料,基本 ...

  5. 关于PHP上传文件时配置 php.ini 中的 upload_tmp_dir

    在<PHP 5.3 入门经典>9.6.3 的试一试中(P235),给出了一个上传文件的例子,这里的文件格式为jpeg图片(image/jpeg).如果之前未配置 php.ini 中的 up ...

  6. php使用curl 实现GET和POST请求(抓取网页,上传文件),支持跨项目和跨服务器

    一:curl 函数和参数详解 函数库:1:curl_init 初始化一个curl会话2:curl_close 关闭一个curl会话3:curl_setopt 为一个curl设置会话参数4:curl_e ...

  7. 阿里云OSS 上传文件SDK

    Aliyun OSS SDK for C# 上传文件 另外:查找的其他实现C#上传文件功能例子: 1.WPF用流的方式上传/显示/下载图片文件(保存在数据库) (文末有案例下载链接) 2.WPF中利用 ...

  8. Java使用HttpURLConnection上传文件(转)

    从普通Web页面上传文件很简单,只需要在form标签叫上enctype="multipart/form-data"即可,剩余工作便都交给浏览器去完成数据收集并发送Http请求.但是 ...

  9. spring mvc(注解)上传文件的简单例子

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...

随机推荐

  1. 在CLion项目中指定不同版本的链接库

    在项目中, 需要使用到libevent-2.1.x, 但是Ubuntu16.04自带的libevent版本为2.0.5, 需要另外编译安装新版的libevent, 安装过程很简单 -stable.ta ...

  2. 转: Orz是一个基于Ogre思想的游戏开发架构

    Orz是一个基于Ogre思想的游戏开发架构,好的结构可以带来更多的功能.Orz和其他的商业以及非商业游戏开发架构不同.Orz更专著于开发者的感受,简化开发者工作.Orz可以用于集成其他Ogre3D之外 ...

  3. 时间选择器(js,css,html)

    忘了从哪下载的了, 整理电脑, 做个记录, 效果图: 下载链接: 链接: https://pan.baidu.com/s/1qfYkcfn8dtLFg0oniB2GHA 提取码: 2amm

  4. easyui的datagrid分页写法小结

    easyui的datagrid分页死活不起作用...沙雕了...不说了上代码 //关闭tab1打开tab2 查询Detail function refundDetail(){ $('#tt').tab ...

  5. c++ ado 程序终止时崩溃

    在_ConnectionPtr析构的时候要将_ConnectionPtr置NULL ADODB::_ConnectionPtr conn;conn.CreateInstance(__uuidof(AD ...

  6. linux中DHCP服务配置文件/etc/dhcpd.conf详细说明

    DHCP服务的配置 dhcpd.conf 是DHCP服务的配置文件,DHCP服务所有参数都是通过修改dhcpd.conf 文件来实现,安装后dhcpd.conf 是没有做任何配置的,将/usr/sha ...

  7. Linux主要shell命令详解(上)

    [摘自网络] kill -9 -1即实现用kill命令退出系统 Linux主要shell命令详解 [上篇] shell是用户和Linux操作系统之间的接口.Linux中有多种shell,其中缺省使用的 ...

  8. JAVA操作mysql

    所需jar包:mysql-connector-java.jar 代码: import java.sql.*; import java.util.ArrayList; import java.util. ...

  9. Ubuntu下看不见pthread_create(安装pthread线程库)

    使用下面的命令就可以了! sudo apt-get install glibc-doc sudo apt-get install manpages-posix-dev 然后在用man -k pthre ...

  10. linux达人养成计划学习笔记(二)—— 文件查找命令

    一.locate命令 1.命令格式: locate 文件名 2.locate在后台数据库中按文件名搜索,速度快,locate命令所搜索的后台数据库 /var/lib/mlocate 3.后台数据库跟新 ...