golang 模拟客户端发送http请求上传文件demo

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/google/uuid"
	"io"
	"log"
	"mime/multipart"
	"net/http"
	"os"
	"path/filepath"
	"strings"
	"time"
)
type Response struct {
	Msg  string `json:"msg"`
	Code int    `json:"code"`
}
func main() {
	var total int
	var response Response
	fmt.Println("是否进行相似度对比,请输入0或者1:  0:不进行对比 | 1:进行对比")
	var isdHash, isNeedChecker, root string
	fmt.Scanln(&isdHash)
	if isdHash == "0" || isdHash == "1" {
		fmt.Println("参数正确:", isdHash)
	} else {
		fmt.Println("参数错误,请重新启动程序")
		time.Sleep(time.Second)
		return
	}
	fmt.Println("是否需要人工审核: 1:需要 | 2:不需要 ")
	fmt.Scanln(&isNeedChecker)
	if isNeedChecker == "1" || isNeedChecker == "2" {
		fmt.Println("参数正确:", isNeedChecker)
	} else {
		fmt.Println("参数错误,请重新启动程序")
		time.Sleep(time.Second)
		return
	}
	fmt.Println("请输入文件目录:")
	fmt.Scanln(&root)
	fmt.Println(root)
	imgFiles := make(map[string]string, 0)
	jsonFiles := make(map[string]string, 0)
	err := getAllFiles(root, imgFiles, jsonFiles)
	if err != nil {
		fmt.Println(err)
		return
	}
	if len(imgFiles) == 0 {
		fmt.Println("该目录下无图片文件!")
		return
	}
	id := uuid.NewString()
	imgLen := len(imgFiles)
	fmt.Println("共有图片:", imgLen, "   |  json文件:", len(jsonFiles))
	extraParams := map[string]string{
		"isdHash":       isdHash,
		"isNeedChecker": isNeedChecker,
		"id":            id,
	}
	for k, v := range imgFiles { 
		request, err := newFileUploadRequest("http://192.168.1.11:8899/dataImport/v1/upload", extraParams, "imgFile", v, "jsonFile", jsonFiles[k])
		if err != nil {
			log.Fatal(err)
		}
		client := &http.Client{}
		resp, err := client.Do(request)
		if err != nil {
			log.Fatal(err)
			return
		} else {
			body := &bytes.Buffer{}
			_, err := body.ReadFrom(resp.Body)
			if err != nil {
				log.Fatal(err)
			}
			json.Unmarshal(body.Bytes(), &response)
			resp.Body.Close()
			if response.Msg == "存在相同图片" {
				total++
				fmt.Println(response.Msg, total)
			}
			if response.Code != http.StatusOK {
				fmt.Println(body)
			}
			imgLen--
			fmt.Println("还剩:", imgLen, " 张图片")
		}
	}
	fmt.Println()

	fmt.Println("------------------")
	fmt.Println("完成,5秒后退出程序")
	time.Sleep(time.Second * 5)
}

func getAllFiles(root string, imgFiles, jsonFiles map[string]string) (err error) {
	dirs, err := os.ReadDir(root)
	if err != nil {
		return err
	}
	for _, v := range dirs {
		if v.IsDir() {
			root2 := root + `\` + v.Name()
			err = getAllFiles(root2, imgFiles, jsonFiles)
		} else {
			switch filepath.Ext(v.Name()) {
			case ".jpg":
				imgFiles[strings.TrimRight(v.Name(), filepath.Ext(v.Name()))] = root + `\` + v.Name()
			case ".json":
				jsonFiles[strings.TrimRight(v.Name(), filepath.Ext(v.Name()))] = root + `\` + v.Name()
			default:
				return
			}
		}
	}
	return
}

// Creates a new file upload http request with optional extra params
func newFileUploadRequest(uri string, params map[string]string, imgFiled, imgPath, jsonFiled, jsonPath string) (*http.Request, error) {
	file, err := os.Open(imgPath)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile(imgFiled, filepath.Base(imgPath))
	if err != nil {
		return nil, err
	}
	_, err = io.Copy(part, file)
	if err != nil {
		return nil, err
	}
	if jsonPath != "" { //有json文件
		file2, err := os.Open(jsonPath)
		if err != nil {
			return nil, err
		}
		defer file2.Close()
		part2, err := writer.CreateFormFile(jsonFiled, filepath.Base(jsonPath))
		if err != nil {
			return nil, err
		}
		_, err = io.Copy(part2, file2)
		if err != nil {
			return nil, err
		}
	}
	for key, val := range params {
		_ = writer.WriteField(key, val)
	}
	err = writer.Close()
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", uri, body)
	//origin := req.Header.Get("Origin")
	//req.Header.Set("Access-Control-Allow-Origin", origin)
	//req.Header.Set("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token,X-Token,X-User-Id")
	//req.Header.Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT")
	//req.Header.Set("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, New-Token, New-Expires-At")
	//req.Header.Set("Access-Control-Allow-Credentials", "true")
	req.Header.Add("Content-Type", writer.FormDataContentType())
	return req, err
}

你可能感兴趣的:(golang,http,java)