不支持带有Content-Type应用程序/钟表流的文件。在Golang发送CSV文件时返回

发布于 2025-02-11 21:11:22 字数 678 浏览 4 评论 0原文

在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())

但是它正在返回:

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

但是,在邮递员的相同电话中,它就成功了吗?有人面对这个吗?

是否有任何方法将内容类型作为“ golang”中的“文本/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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

殊姿 2025-02-18 21:11:22

要设置内容类型,请直接调用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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文