seaweedfs/weed-fs/src/pkg/operation/upload_content.go

43 lines
996 B
Go
Raw Normal View History

2012-09-21 08:58:29 +08:00
package operation
import (
2012-09-26 18:27:10 +08:00
"bytes"
"encoding/json"
_ "fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
2012-09-21 08:58:29 +08:00
)
type UploadResult struct {
2012-09-26 18:27:10 +08:00
Size int
2012-09-21 08:58:29 +08:00
}
func Upload(uploadUrl string, filename string, reader io.Reader) (*UploadResult, error) {
2012-09-26 18:27:10 +08:00
body_buf := bytes.NewBufferString("")
body_writer := multipart.NewWriter(body_buf)
file_writer, err := body_writer.CreateFormFile("file", filename)
io.Copy(file_writer, reader)
content_type := body_writer.FormDataContentType()
body_writer.Close()
resp, err := http.Post(uploadUrl, content_type, body_buf)
if err != nil {
println("uploading to", uploadUrl)
return nil, err
}
defer resp.Body.Close()
resp_body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var ret UploadResult
err = json.Unmarshal(resp_body, &ret)
if err != nil {
println("upload response to", uploadUrl, resp_body)
panic(err.Error())
}
//fmt.Println("Uploaded " + strconv.Itoa(ret.Size) + " Bytes to " + uploadUrl)
return &ret, nil
2012-09-21 08:58:29 +08:00
}