英文:
"File with content-type application/octet-stream is not supported" returned on sending CSV file in Golang
问题
在Golang中调用API端点时,我将CSV文件作为参数传递:
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())
但是返回的错误是:
不支持内容类型为application/octet-stream的文件
但是在POSTMAN中进行相同的调用却成功了?有人遇到过这个问题吗?
在Golang中有没有办法将内容类型设置为"text/csv"来传递文件?
英文:
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?
答案1
得分: 1
要设置内容类型,请直接调用CreatePart方法,而不是CreateFormFile辅助函数:
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)
如果您没有使用字符串字面量作为问题中所示,请对字段名和文件名进行转义。请参考CreateFormFile实现的示例,了解如何进行转义。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论