LoginSignup
1
1

More than 3 years have passed since last update.

Golangでファイルをアップロードする時にContent-Typeを指定する方法

Last updated at Posted at 2019-10-03

はじめに

個人的なメモが目的。

よくある実装

body := new(bytes.Buffer)
multipartWriter := multipart.NewWriter(body)
fileWriter, _ := multipartWriter.CreateFormFile(fieldName, fileName)

_, _ = io.Copy(fileWriter, file)

ただ、これだとファイルを受け取った側で Content-Type: application/octet-stream となってしまい、Content-Typeを判断することができない。

解決案

Golangの内部の実装を参考にやってみた。

body := new(bytes.Buffer)
multipartWriter := multipart.NewWriter(body)

contentType := func() string {
    defer func() {
        _ = file.Seek(0, 0)
    }()

    fileData, err := ioutil.ReadAll(file)
    if err != nil {
        return "application/octet-stream"
    }

    return http.DetectContentType(fileData)
}()

header := make(textproto.MIMEHeader)
header.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="%s"; filename="%s"`, fieldName, fileName))
header.Set("Content-Type", contentType)
part, _ := multipartWriter.CreatePart(header)

_, _ = io.Copy(part, file)

最後に

他にいい方法あったらコメントお願いします。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1