Table of Contents
Correct Answer
Home Backend Development Golang Golang uses multipart to upload large files to external API. How to avoid `io.Copy(io.Writer, io.Reader)` problems

Golang uses multipart to upload large files to external API. How to avoid `io.Copy(io.Writer, io.Reader)` problems

Feb 06, 2024 am 09:45 AM
api call

Golang 使用多部分将大文件上传到外部 API。如何避免`io.Copy(io.Writer, io.Reader)`问题

Question content

My goal is to use golang's built-in net/http package to upload a large file to POST https://somehost /media .

HTTP format for Api call

POST /media HTTP/1.1
Host: somehost
Content-Length: 434
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="detail"

More and more detail
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="file"; filename="some_big_video.mp4"
Content-Type: <Content-Type header here>

(data)
------WebKitFormBoundary7MA4YWxkTrZu0gW--
Copy after login

In golang, this is the code.

package main

import (
  "fmt"
  "bytes"
  "mime/multipart"
  "os"
  "path/filepath"
  "io"
  "net/http"
  "io/ioutil"
)

func main() {

  url := "https://somehost/media"
  method := "POST"

  payload := &bytes.Buffer{}
  writer := multipart.NewWriter(payload)
  _ = writer.WriteField("details", "more and more details")
  file, errFile3 := os.Open("/Users/vajahat/Downloads/some_big_video.mp4")
  defer file.Close()
  part3,errFile3 := writer.CreateFormFile("file","some_big_video.mp4") 
  _, errFile3 = io.Copy(part3, file)
  if errFile3 != nil {
    fmt.Println(errFile3)
    return
  }
  err := writer.Close()
  if err != nil {
    fmt.Println(err)
    return
  }
  client := &http.Client {}
  req, err := http.NewRequest(method, url, payload)

  if err != nil {
    fmt.Println(err)
    return
  }

  req.Header.Set("Content-Type", writer.FormDataContentType())
  res, err := client.Do(req)
  if err != nil {
    fmt.Println(err)
    return
  }
  defer res.Body.Close()

  body, err := ioutil.ReadAll(res.Body)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(body))
}
Copy after login

How to avoidio.Copy(io.Writer, io.Reader)Problems

The above code works fine, but on the line _, errFile3 = io.Copy(part3, file). This essentially copies everything in the file into main memory.

How to avoid this situation?

Is there any way I can stream large files to the api via multipart-formdata?

The program will be run on the remote server. May crash if opening a very large file.


Correct Answer


Use io.Pipe and a goroutine to copy the file to the request without loading the entire file in memory.

pr, pw := io.Pipe()
writer := multipart.NewWriter(pw)
ct := writer.FormDataContentType()
go func() {
    _ = writer.WriteField("details", "more and more details")
    file, err := os.Open("/Users/vajahat/Downloads/some_big_video.mp4")
    if err != nil {
        pw.CloseWithError(err)
        return
    }
    defer file.Close()
    part3, err := writer.CreateFormFile("file", "some_big_video.mp4")
    if err != nil {
        pw.CloseWithError(err)
        return
    }
    _, err = io.Copy(part3, file)
    if err != nil {
        pw.CloseWithError(err)
        return
    }
    pw.CloseWithError(writer.Close())
}()

client := &http.Client{}
req, err := http.NewRequest(method, url, pr)

if err != nil {
    fmt.Println(err)
    return
}

req.Header.Set("Content-Type", ct)
// remaining code as before
Copy after login

The above is the detailed content of Golang uses multipart to upload large files to external API. How to avoid `io.Copy(io.Writer, io.Reader)` problems. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Exploring the boundaries of agents: AgentQuest, a modular benchmark framework for comprehensively measuring and improving the performance of large language model agents Exploring the boundaries of agents: AgentQuest, a modular benchmark framework for comprehensively measuring and improving the performance of large language model agents Apr 11, 2024 pm 08:52 PM

Based on the continuous optimization of large models, LLM agents - these powerful algorithmic entities have shown the potential to solve complex multi-step reasoning tasks. From natural language processing to deep learning, LLM agents are gradually becoming the focus of research and industry. They can not only understand and generate human language, but also formulate strategies, perform tasks in diverse environments, and even use API calls and coding to Build solutions. In this context, the introduction of the AgentQuest framework is a milestone. It not only provides a modular benchmarking platform for the evaluation and advancement of LLM agents, but also provides researchers with a Powerful tools to track and improve the performance of these agents at a more granular level

Can software compiled by Mingw be used in a Linux environment? Can software compiled by Mingw be used in a Linux environment? Mar 20, 2024 pm 05:06 PM

Can software compiled by Mingw be used in a Linux environment? Mingw is a tool chain used on the Windows platform to compile and generate programs that can run on Windows. So, can the software compiled by Mingw be used in the Linux environment? The answer is yes, but it requires some extra work and steps. The most common way to run programs compiled on Windows on Linux is to use Wine. Wine is a tool used in Linux and other similar Un

How to use PHP to call web services and APIs? How to use PHP to call web services and APIs? Jun 30, 2023 pm 03:03 PM

How to use PHP's Web services and API calls With the continuous development of Internet technology, Web services and API calls have become an indispensable part of developers. By using web services and API calls, we can easily interact with other applications to obtain data or implement specific functions. As a popular server-side scripting language, PHP also provides a wealth of functions and tools to support the development of Web services and API calls. In this article, I will briefly introduce how to use PHP to

View your Litecoin wallet address View your Litecoin wallet address Apr 07, 2024 pm 05:12 PM

To view the Litecoin wallet address, visit the Litecoin wallet and look for the address in the "Receive" tab; you can also use a blockchain browser or API call.

Let Siri no longer be mentally retarded! Apple defines a new client-side model, which is 'much better than GPT-4. It gets rid of text and visually simulates screen information. The minimum parameter model is still 5% better than the baseline system. Let Siri no longer be mentally retarded! Apple defines a new client-side model, which is 'much better than GPT-4. It gets rid of text and visually simulates screen information. The minimum parameter model is still 5% better than the baseline system. Apr 02, 2024 pm 09:20 PM

Written by Noah | 51CTO Technology Stack (WeChat ID: blog51cto) Siri, who is always criticized by users as "a bit mentally retarded", can be saved! Siri has been one of the representatives in the field of intelligent voice assistants since its birth, but its performance has been unsatisfactory for a long time. However, the latest research results released by Apple's artificial intelligence team are expected to significantly change the status quo. These results are exciting and raise great expectations for the future of this field. In related research papers, Apple's AI experts describe a system in which Siri can do more than just identify content in images, becoming smarter and more useful. This functional model is called ReALM, which is based on the GPT4.0 standard and has a

Summary of FAQs for DeepSeek usage Summary of FAQs for DeepSeek usage Feb 19, 2025 pm 03:45 PM

DeepSeekAI Tool User Guide and FAQ DeepSeek is a powerful AI intelligent tool. This article will answer some common usage questions to help you get started quickly. FAQ: The difference between different access methods: There is no difference in function between web version, App version and API calls, and App is just a wrapper for web version. The local deployment uses a distillation model, which is slightly inferior to the full version of DeepSeek-R1, but the 32-bit model theoretically has 90% full version capability. What is a tavern? SillyTavern is a front-end interface that requires calling the AI ​​model through API or Ollama. What is breaking limit

PHP Kuaishou API interface calling skills: how to handle the error information returned by the interface PHP Kuaishou API interface calling skills: how to handle the error information returned by the interface Jul 20, 2023 pm 11:22 PM

PHP Kuaishou API interface calling tips: How to handle the error information returned by the interface When using PHP to call the Kuaishou API interface, we often encounter situations where the interface returns errors. For error information returned by the processing interface, we need to provide appropriate processing and feedback to improve the stability and user experience of the application. This article will introduce some techniques for handling error information returned by interfaces and provide corresponding code examples. Use try-catch to catch exceptions. When calling the API interface, some exception errors may occur.

Golang uses multipart to upload large files to external API. How to avoid `io.Copy(io.Writer, io.Reader)` problems Golang uses multipart to upload large files to external API. How to avoid `io.Copy(io.Writer, io.Reader)` problems Feb 06, 2024 am 09:45 AM

My goal is to upload a large file to POST https://somehost/media using golang's built-in net/http package. HTTP format POST/mediaHTTP/1.1Host:somehostContent-Length:434Content-Type:multipart/form-data;boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW------WebKitFormBoundary7MA4YWxkTr

See all articles