简体   繁体   中英

"File with content-type application/octet-stream is not supported" returned on sending CSV file in Golang

On making an API call to and endpoint in Golang I am passing CSV file as:

payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)

file, _ := os.Open("temp.csv")
defer file.Close()
part3,
    errFile3 := writer.CreateFormFile("file", filepath.Base("temp.csv"))
_, errFile3 = io.Copy(part3, file)
if errFile3 != nil {
    fmt.Println(errFile3)
    return
}
_ = writer.Close()
req, _ := http.NewRequest("POST", url, payload)
req.Header.Set("Content-Type", writer.FormDataContentType())

But it is returning:

File with content-type application/octet-stream is not supported

But on making the same call from POSTMAN it is succeeding? Has anyone faced this?

Is there any way of passing content type as "text/csv" in Golang for file?

To set the content type, call the CreatePart method directly instead of the CreateFormFile helper function:

h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",`form-data; name="file"; filename="temp.csv"`)
h.Set("Content-Type", "text/csv")
part3, errFile3 := writer.CreatePart(h)

Escape the field name and file name if you are not using string literals as shown in the question. See the CreateFormFile implementation for an example of how to do the escaping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM