Last active
May 27, 2017 07:22
-
-
Save huyinghuan/0fba118841f80fdcbeea9d0e34f9e28d to your computer and use it in GitHub Desktop.
go文件上传
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" | |
"log" | |
"mime/multipart" | |
"net/http" | |
"os" | |
"path/filepath" | |
"strings" | |
"sync" | |
"time" | |
) | |
func upload(wg *sync.WaitGroup, file string) { | |
defer wg.Done() | |
url := "https://u.heartwith.me" | |
var b bytes.Buffer | |
w := multipart.NewWriter(&b) | |
// Add your image file | |
f, err := os.Open(file) | |
if err != nil { | |
log.Fatalln(err) | |
return | |
} | |
defer f.Close() | |
fw, err := w.CreateFormFile("assert", file) | |
if err != nil { | |
log.Fatalln(err) | |
return | |
} | |
if _, err = io.Copy(fw, f); err != nil { | |
log.Fatalln(err) | |
return | |
} | |
// Don't forget to close the multipart writer. | |
// If you don't close it, your request will be missing the terminating boundary. | |
w.Close() | |
// Now that you have a form, you can submit it to your handler. | |
req, err := http.NewRequest("POST", url, &b) | |
if err != nil { | |
log.Fatalln(err) | |
return | |
} | |
// Don't forget to set the content type, this will contain the boundary. | |
req.Header.Set("Content-Type", w.FormDataContentType()) | |
// Submit the request | |
client := &http.Client{} | |
res, err := client.Do(req) | |
if err != nil { | |
log.Fatalln(err) | |
return | |
} | |
if res.StatusCode != http.StatusOK { | |
err = fmt.Errorf("bad status: %s", res.Status) | |
} | |
log.Printf("Send %s success\n", file) | |
return | |
} | |
func exists(fileName string) int { | |
suffixQueue := []string{".png", ".jpeg", ".jpg"} | |
for _, value := range suffixQueue { | |
if strings.Index(fileName, value) != -1 { | |
return 1 | |
} | |
} | |
return -1 | |
} | |
func main() { | |
dir, err := filepath.Abs(filepath.Dir(os.Args[0])) | |
if err != nil { | |
log.Fatal(err) | |
} | |
files, _ := ioutil.ReadDir(dir) | |
var wg sync.WaitGroup | |
matchFile := []string{} | |
for _, f := range files { | |
fileName := f.Name() | |
if exists(fileName) != -1 { | |
matchFile = append(matchFile, (dir + "/" + fileName)) | |
continue | |
} | |
} | |
wg.Add(len(matchFile)) | |
for _, fileName := range matchFile { | |
go upload(&wg, fileName) | |
} | |
wg.Wait() | |
fmt.Println("上传完成") | |
time.Sleep(3 * time.Second) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment