小文件上传
var buffer bytes.Buffer
w := multipart.NewWriter(&buffer)
// Write fields and files
w.CreateFormField("input1")
w.WriteField("input1","value1")
w.CreateFormFile("file","filename.dat")
resp,err := http.Post(url,w.FormDataContentType(),&buffer)
服务器的handler:
func uploadHandler(w http.ResponseWriter, r *http.Request){
if r.URL.Path=="/upload.go" {
fn,header,err:=r.FormFile("file")
defer fn.Close()
f,err:=os.Create("filenametosaveas")
defer f.Close()
io.Copy(f,fn)
}
}
客户端代码:
func Upload() (err error) {
// Create buffer
buf := new(bytes.Buffer) // caveat IMO dont use this for large files, \
// create a tmpfile and assemble your multipart from there (not tested)
w := multipart.NewWriter(buf)
// Create file field
fw, err := w.CreateFormFile("file", "helloworld.go") //这里的file很重要,必须和服务器端的FormFile一致
if err != nil {
fmt.Println("c")
return err
}
fd, err := os.Open("helloworld.go")
if err != nil {
fmt.Println("d")
return err
}
defer fd.Close()
// Write file field from file to upload
_, err = io.Copy(fw, fd)
if err != nil {
fmt.Println("e")
return err
}
// Important if you do not close the multipart writer you will not have a
// terminating boundry
w.Close()
req, err := http.NewRequest("POST","http://192.168.2.127/configure.go?portId=2", buf)
if err != nil {
fmt.Println("f")
return err
}
req.Header.Set("Content-Type", w.FormDataContentType())
var client http.Client
res, err := client.Do(req)
if err != nil {
fmt.Println("g")
return err
}
io.Copy(os.Stderr, res.Body) // Replace this with Status.Code check
fmt.Println("h")
return err
}
html上传,原文
package main
import (
"fmt"
"io"
"net/http"
"log"
)
// 获取大小的接口
type Sizer interface {
Size() int64
}
// hello world, the web server
func HelloServer(w http.ResponseWriter, r *http.Request) {
if "POST" == r.Method {
file, _, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(), 500)
return
}
defer file.Close()
f,err:=os.Create("filenametosaveas")
defer f.Close()
io.Copy(f,file)
fmt.Fprintf(w, "上传文件的大小为: %d", file.(Sizer).Size())
return
}
// 上传页面
w.Header().Add("Content-Type", "text/html")
w.WriteHeader(200)
html := `
<form enctype="multipart/form-data" action="/hello" method="POST">
Send this file: <input name="file" type="file" />
<input type="submit" value="Send File" />
</form>
`
io.WriteString(w, html)
}
func main() {
http.HandleFunc("/hello", HelloServer)
err := http.ListenAndServe(":12345", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
大文件上传
关键的不同是io.MultiReader
package main
import (
"fmt"
"net/http"
"mime/multipart"
"bytes"
"os"
"io"
)
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("upfile", 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
}
defer fh.Close()
// 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(close_string)
// 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)
}