岛屿可以找到海
岛屿可以找到海

golang发送multipart/form-data请求

//创建一个指针类型的bytes.Buffer缓冲区
payload := &bytes.Buffer{}
                //创建一个writer对象写入form-data请求的数据
		writer := multipart.NewWriter(payload)

		// 添加文本字段
		_ = writer.WriteField("purpose", "file-extract")

		// 添加文件字段,打开一个文件,返回一个io流
		file, err := uploadFile.Open()
		if err != nil {
			fmt.Println("Error opening file:", err)
			return
		}
		defer file.Close()
                
                //设置请求的文件字段和文件名称,返回一个可写入的io对象
		part, err := writer.CreateFormFile("file", uploadFile.Filename)
		if err != nil {
			fmt.Println("Error creating form file:", err)
			return
		}
                
                //将文件复制写入到part中
		_, err = io.Copy(part, file)
		if err != nil {
			fmt.Println("Error copying file content:", err)
			return
		}

		err = writer.Close()
		if err != nil {
			fmt.Println("Error closing writer:", err)
			return
		}

		client := &http.Client{}
		req, err := http.NewRequest("POST", "https://api.moonshot.cn/v1/files", payload)

		if err != nil {
			fmt.Println("Error creating request:", err)
			return
		}
                
                //获取表单请求体中的数据类型并设置到请求头,类似于:multipart/form-data; boundary=someBoundaryValue
		req.Header.Set("Content-Type", writer.FormDataContentType())
		req.Header.Set("Authorization", "Bearer sk-Oe1x07JX1nyGHCEDnUoXmsBhQTYc0DwhI4t9gD4nnGfVfomh")

		res, err := client.Do(req)
		if err != nil {
			fmt.Println("Error sending request:", err)
			return
		}
		defer res.Body.Close()

		body, err := io.ReadAll(res.Body)
		if err != nil {
			fmt.Println("Error reading response body:", err)
			return
		}

岛屿可以找到海

golang发送multipart/form-data请求
//创建一个指针类型的bytes.Buffer缓冲区 payload := &bytes.Buffer{} //创建一个writer对象写入form-data请求的数据 writer := multipart.NewWriter(payload) …
扫描二维码继续阅读
2024-07-23