golangはフォームを使用してファイルをアップロードします

golangアップロードファイル

// import github.com/fwhezfwhez/errorx
func GenerateFileAndUpload(filePath string, url string, args map[string]string, resp interface{
    
    }) error {
    
    
	bodyBuffer := &bytes.Buffer{
    
    }
	bodyWriter := multipart.NewWriter(bodyBuffer)

	info, e := os.Stat(filePath)
	if e == os.ErrNotExist {
    
    
		return errorx.NewFromStringf("file %s not exist", filePath)
	}
	if info.IsDir() {
    
    
		return errorx.NewFromStringf("path %s is a directory not a file", filePath)
	}

	fileWriter1, e := bodyWriter.CreateFormFile("file", info.Name())
	if e != nil {
    
    
		return errorx.Wrap(e)
	}
	fmt.Println("fileName", info.Name())
	file1, e := os.Open(filePath)
	if e != nil {
    
    
		return errorx.Wrap(e)
	}
	defer file1.Close()
	_, e = io.Copy(fileWriter1, file1)
	if e != nil {
    
    
		return errorx.Wrap(e)
	}

	for key, value := range args {
    
    
		e = bodyWriter.WriteField(key, value)
		if e != nil {
    
    
			return errorx.Wrap(e)
		}
	}

	contentType := bodyWriter.FormDataContentType()
	bodyWriter.Close()

	req, e := http.NewRequest("POST", url, bodyBuffer)
	if e != nil {
    
    
		return errorx.Wrap(e)
	}

	req.Header.Set("Content-Type", contentType)
	res, e := c.Do(req)
	if e != nil {
    
    
		return errorx.Wrap(e)
	}
	if res == nil {
    
    
		return errorx.NewFromString("resp nil")
	}
	if res.Body == nil {
    
    
		return errorx.NewFromString("response.body nil")
	}

	defer res.Body.Close()

	buf, e := ioutil.ReadAll(res.Body)

	if e != nil {
    
    
		return errorx.Wrap(e)
	}

	if res.StatusCode != 200 {
    
    
		if len(buf) > 200 {
    
    
			return errorx.NewFromStringf("recv status %d, body \n%s", res.StatusCode, buf[:199])
		} else {
    
    
			return errorx.NewFromStringf("recv status %d, body \n%s", res.StatusCode, buf)
		}
	}

	if e := json.Unmarshal(buf, resp); e != nil {
    
    
		if len(buf) > 200 {
    
    
			return errorx.NewFromStringf("marshal error '%v', body '%s'", e, buf[:199])
		}
		return errorx.NewFromStringf("marshal error '%v', body '%s'", e, buf)
	}
	return nil
}

使用する

func TestGenerateFileAndUpload(t *testing.T) {
    
    
	var filePath = "G:\\go_workspace\\GOPATH\\src\\shangraomajiang\\util\\common\\util\\utils.go"
	var url = "http://localhost:8080/upload"
	var resp map[string]interface{
    
    }
	if e := GenerateFileAndUpload(filePath, url, map[string]string{
    
    
		"game_id": "78",
		"user_id": "10086",
		"key":     "activate_code1",
	}, &resp); e != nil {
    
    
		fmt.Println(e.Error())
		return
	}
	fmt.Println(resp)
}

おすすめ

転載: blog.csdn.net/fwhezfwhez/article/details/105076460