golang中post提交参数同时含有文件上传功能(千万要注意设置header的方法,不能随便写)

func post_data(url string, json string, filename string, filepath string) {
    var buff bytes.Buffer
    // 创建一个Writer
    writer := multipart.NewWriter(&buff)

    // 写入一般的表单字段
    writer.WriteField("json", json)

    // 写入文件字段
    if checkFileIsExist(filepath) {
        // CreateFormFile 第一个参数是表单对应的字段名;第二个字段是对应上传文件的名称
        w, err := writer.CreateFormFile("file", filename)
        if err != nil {
            //创建文件失败
            checkErr(err)
            return
        }
        data, err := ioutil.ReadFile(filepath)
        if err != nil {
            //读取文件发生错误
            checkErr(err)
            return
        }
        // 把文件内容写入cd
        w.Write(data)
    }

    writer.Close()

    // 发送一个POST请求
    req, err := http.NewRequest("POST", url, &buff)
    if err != nil {
        //创建请求失败
        checkErr(err)
    }

    // 设置你需要的Header(不要想当然的手动设置Content-Type)
    req.Header.Set("Content-Type", writer.FormDataContentType())
    //req.Header.Set("Content-Type", "application/json;charset=UTF-8")
    //req.Header.Set("Content-Type", "text/html;charset=utf-8")

    //req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36 Edg/85.0.564.44")

    var client http.Client
    // 执行请求
    resp, err := client.Do(req)
    defer resp.Body.Close()
    // 读取返回内容
    d, err := ioutil.ReadAll(resp.Body)
    if err != nil{
        //读取失败
        checkErr(err)
        return
    }

    fmt.Println(string(d))

}

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,下面是一个示例代码,使用 `gin` 框架实现分片上传阿里云OSS功能: ```go package main import ( "fmt" "io" "log" "net/http" "os" "path/filepath" "strconv" "github.com/aliyun/aliyun-oss-go-sdk/oss" "github.com/gin-gonic/gin" ) const ( MaxUploadSize = 5 * 1024 * 1024 * 1024 // 5 GB ChunkSize = 10 * 1024 * 1024 // 10 MB ) func main() { r := gin.Default() r.POST("/upload", UploadHandler) if err := r.Run(":8080"); err != nil { log.Fatal(err) } } func UploadHandler(c *gin.Context) { file, header, err := c.Request.FormFile("file") if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } defer file.Close() fileSize, err := strconv.Atoi(c.Request.FormValue("size")) if err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } fileName := header.Filename filePath := filepath.Join(os.TempDir(), fileName) dst, err := os.Create(filePath) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } defer dst.Close() if _, err := io.Copy(dst, file); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } if int64(fileSize) > MaxUploadSize { c.JSON(http.StatusBadRequest, gin.H{"error": "file size exceeds the maximum limit"}) return } client, err := oss.New("oss-cn-hangzhou.aliyuncs.com", "<access_key>", "<access_secret>") if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } bucket, err := client.Bucket("<bucket_name>") if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } chunkSize := ChunkSize totalPartsNum := (fileSize + chunkSize - 1) / chunkSize objectName := fileName // Initiate the multipart upload imur, err := bucket.InitiateMultipartUpload(objectName) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } var uploadedParts []oss.UploadPart var partNumber int // Upload each part for i := 0; i < totalPartsNum; i++ { partSize := chunkSize if i == totalPartsNum-1 { partSize = fileSize - i*chunkSize } partNumber = i + 1 // Open the file and read the bytes file, err := os.Open(filePath) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } defer file.Close() // Seek to the start of the part offset := int64(i * chunkSize) if _, err := file.Seek(offset, io.SeekStart); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } // Read the part into memory partBuffer := make([]byte, partSize) if _, err := file.Read(partBuffer); err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } // Upload the part to OSS uploadPart, err := bucket.UploadPart(imur, partBuffer, partNumber) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } uploadedParts = append(uploadedParts, uploadPart) } // Complete the multipart upload cmur, err := bucket.CompleteMultipartUpload(imur, uploadedParts) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } fmt.Println(cmur) c.JSON(http.StatusOK, gin.H{"message": "upload success"}) } ``` 以上代码,实现了以下功能: 1. 从请求获取文件和大小 2. 将文件存储到本地磁盘 3. 初始化分片上传,并上传每个分片 4. 完成分片上传,将分片合并成一个对象 需要注意的是,代码使用了阿里云OSS的 SDK 进行操作,因此需要先在阿里云控制台上创建 OSS Bucket,并在代码正确的 access_key、access_secret 和 bucket_name。 另外,由于上传的文件可能很大,因此需要设置分片大小,本例设置为每个分片的大小为10MB。同时,为了避免服务器崩溃,还需要设置文件大小的最大限制,本例设置为5GB。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

扬子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值