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.