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

43 lines
955 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"
2012-09-27 04:38:45 +08:00
"log"
2012-09-26 18:27:10 +08:00
"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 {
2012-09-27 04:38:45 +08:00
log.Println("failing to upload to", uploadUrl)
2012-09-26 18:27:10 +08:00
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 {
2012-09-27 04:38:45 +08:00
log.Println("failing to read upload resonse", uploadUrl, resp_body)
return nil, err
2012-09-26 18:27:10 +08:00
}
return &ret, nil
2012-09-21 08:58:29 +08:00
}