📂

【Go】Echoでファイルを通信する方法【Multipart/form,Base64】

2023/11/30に公開

GoのフレームワークとしてEchoを使っていて、PDFなどのファイルをフロントエンドへ返す方法をご紹介します。

// ファイルを受信

fileName := "file名を追加(例:"file")

fileParam, err := c.FormFile(fileName)
if err != nil {
	return err
}

// fileはmultipart.File型
file, err := fileParam.Open()
if err != nil {
	return err
}

一方、ファイルを送信する際は、このような形になります。

// ファイルを送信
func renderFile(c echo.Context, filePath string) error {
	err := c.File(filePath)
	if err != nil {
		return err
	}
	return nil
}

ちなみに、ファイルに名前などのオプションをつけてレスポンスする場合ですが、以下のコードで実装可能です。

c.Attribute(context, filePath, fileName)

ファイルを「添付ファイル」としてクライアントに送信する場合はこの辺りが使えそう。

// Attachment sends a response as attachment, prompting client to save the
// file.
Attachment(file string, name string) error

ファイルがブラウザ内で直接開く場合。

// Inline sends a response as inline, opening the file in the browser.
Inline(file string, name string) error

もし、この他に良い方法やechoで使えそうな処理があれば、コメントいただければと思います!

GitHubで編集を提案

Discussion