0

I need to send a POST request to some API which accepts only file as multipart/form-data. But I have the data as []byte. Now what I can do is write this []byte data to a temporary file and then send that file. After some googling I found this code to upload file:

fileDir, _ := os.Getwd()
fileName := "upload-file.txt"
filePath := path.Join(fileDir, fileName)

file, _ := os.Open(filePath)
defer file.Close()

body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, _ := writer.CreateFormFile("file", filepath.Base(file.Name()))
io.Copy(part, file)
writer.Close()

r, _ := http.NewRequest("POST", "http://example.com", body)
r.Header.Add("Content-Type", writer.FormDataContentType())
client := &http.Client{}
client.Do(r)

After some more googling I learned this. Seems to me for sending files we only need file name and content (maybe size). All these data I can provide without creating a temporary file, writing to that file and then again reading back from that file.

Is it possible to do so? Can I send []bytes as a file somehow? A working example is much appreciated.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
John Reese
  • 31
  • 4

1 Answers1

2

Write the []byte directly to the part. Use this code to write the slice content to the part and post the form:

body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, _ := writer.CreateFormFile("file", "insert-name-here")
part.Write(content) // <-- content is the []byte
writer.Close()

r, _ := http.NewRequest("POST", "http://example.com", body)
r.Header.Add("Content-Type", writer.FormDataContentType())
err := http.DefaultClient.Do(r)
if err != nil {
   // handle error
}
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242