seaweedfs/weed/operation/upload_content.go

48 lines
1 KiB
Go
Raw Normal View History

2012-09-21 00:58:29 +00:00
package operation
import (
2012-09-26 10:27:10 +00:00
"bytes"
"encoding/json"
2013-01-17 08:56:56 +00:00
"errors"
2012-09-26 10:27:10 +00:00
_ "fmt"
"io"
"io/ioutil"
2013-01-17 08:56:56 +00:00
"log"
2012-09-26 10:27:10 +00:00
"mime/multipart"
"net/http"
2012-09-21 00:58:29 +00:00
)
type UploadResult struct {
2013-01-17 08:56:56 +00:00
Size int
Error string
2012-09-21 00:58:29 +00:00
}
func Upload(uploadUrl string, filename string, reader io.Reader) (*UploadResult, error) {
2012-09-26 10:27:10 +00: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 {
2013-01-17 08:56:56 +00:00
log.Println("failing to upload to", uploadUrl)
2012-09-26 10:27:10 +00: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 {
2013-01-17 08:56:56 +00:00
log.Println("failing to read upload resonse", uploadUrl, resp_body)
return nil, err
2012-09-26 10:27:10 +00:00
}
2013-01-17 08:56:56 +00:00
if ret.Error != "" {
return nil, errors.New(ret.Error)
2012-09-26 21:28:46 +00:00
}
2012-09-26 10:27:10 +00:00
return &ret, nil
2012-09-21 00:58:29 +00:00
}