123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130 |
- package main
- import (
- "bytes"
- "fmt"
- "io"
- "io/ioutil"
- "mime/multipart"
- "net/http"
- "os"
- "path"
- "strings"
- "github.com/spf13/viper"
- )
- func main() {
- postFormDataWithMultipartFile()
- }
- func readDir(dirname string) ([]string, error) {
- infos, err := ioutil.ReadDir(dirname)
- if err != nil {
- fmt.Println("file read Error!")
- fmt.Printf("%s", err)
- return nil, err
- }
- // names := make([]string, len(infos))
- var names []string
- for _, info := range infos {
- fileType := path.Ext(info.Name())
- if len(fileType) != 0 {
- fileType = strings.ToLower(fileType)
- if fileType == ".pdf" {
- names = append(names, info.Name())
- }
- }
- // names[i] = info.Name()
- }
- return names, nil
- }
- func remove(file string) {
- err := os.Remove(file) //删除文件test.txt
- if err != nil {
- //如果删除失败则输出 file remove Error!
- fmt.Println("file remove Error!", err)
- } else {
- //如果删除成功则输出 file remove OK!
- fmt.Println("file remove OK!", file)
- }
- }
- func postFormDataWithMultipartFile() {
- fmt.Println("=======start=======")
- config := viper.New()
- // config.AddConfigPath("./config/")
- // config.SetConfigName("config")
- // config.SetConfigType("yaml")
- config.SetConfigFile("./config/config.yaml")
- config.ReadInConfig()
- postURL := config.GetString("postURL")
- pdfPath := config.GetString("pdfPath")
- // postURL := "http://localhost:8080/api/tpsUpload"
- fmt.Println("load yml postURL: ", postURL)
- fmt.Println("load yml pdfPath: ", pdfPath)
- fileNames, _ := readDir(pdfPath)
- fmt.Println(fileNames)
- defer func() {
- for _, val := range fileNames {
- remove(pdfPath + val)
- }
- }()
- client := http.Client{}
- bodyBuf := &bytes.Buffer{}
- bodyWrite := multipart.NewWriter(bodyBuf)
- for _, val := range fileNames {
- file, err := os.Open(pdfPath + val)
- if err != nil {
- fmt.Println("err1")
- fmt.Printf("%s", err)
- }
- defer file.Close()
- fileWrite, _ := bodyWrite.CreateFormFile("files", val)
- _, err = io.Copy(fileWrite, file)
- if err != nil {
- fmt.Println("err2")
- fmt.Printf("%s", err)
- }
- }
- bodyWrite.Close() //要关闭,会将w.w.boundary刷写到w.writer中
- // 创建请求
- req, err := http.NewRequest(http.MethodPost, postURL, bodyBuf)
- if err != nil {
- fmt.Println("err3")
- fmt.Printf("%s", err)
- }
- // 设置头
- contentType := bodyWrite.FormDataContentType()
- req.Header.Set("Content-Type", contentType)
- resp, err := client.Do(req)
- if err != nil {
- fmt.Println("err4")
- fmt.Printf("%s", err)
- }
- defer resp.Body.Close()
- // defer req.Body.Close()
- b, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- fmt.Println("err5")
- fmt.Printf("%s", err)
- }
- fmt.Println(string(b))
- // client.CloseIdleConnections()
- fmt.Println("=======end=======")
- }
|