Created
December 17, 2014 05:26
-
-
Save mozillazg/c43d8690e3460c2e4ffd to your computer and use it in GitHub Desktop.
Upload file by go. Don't support custom headers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"mime/multipart" | |
"net/http" | |
"os" | |
) | |
const upUrl string = "http://www.bild.me/index.php" | |
func upload(url string, data map[string]string, | |
paramname string, filename string, | |
) error { | |
bodyBuf := &bytes.Buffer{} | |
bodyWriter := multipart.NewWriter(bodyBuf) | |
fileWriter, err := bodyWriter.CreateFormFile(paramname, filename) | |
if err != nil { | |
fmt.Println("error writing to buffer") | |
return err | |
} | |
f, err := os.Open(filename) | |
if err != nil { | |
fmt.Println("error open file") | |
return err | |
} | |
_, err = io.Copy(fileWriter, f) | |
if err != nil { | |
return err | |
} | |
for k, v := range data { | |
bodyWriter.WriteField(k, v) | |
} | |
contentType := bodyWriter.FormDataContentType() | |
bodyWriter.Close() | |
resp, err := http.Post(url, contentType, bodyBuf) | |
if err != nil { | |
return err | |
} | |
defer resp.Body.Close() | |
respBody, err := ioutil.ReadAll(resp.Body) | |
if err != nil { | |
return err | |
} | |
fmt.Println(resp.StatusCode) | |
fmt.Println(string(respBody)) | |
return nil | |
} | |
func main() { | |
data := map[string]string{ | |
"t": "1", | |
"C1": "ON", | |
"upload": "1", | |
// "F1": "hello", | |
} | |
upload(upUrl, data, "F1", "up-download.jpg") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment