iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 25
1
Modern Web

Iris這個在go語言上地表最快的網頁框架系列 第 25

iris 的 file upload

file upload

在介紹完使用者提交請求的處理方式之後,接下來要介紹一個很常會應用到的功能,那就是上傳檔案,接下來跟大家介紹如何處理上傳檔案的請求。

本文同步放置於此

iris file upload

相信大家應該常遇到上傳照片或其他檔案的請求,今天來跟大家介紹在iris裡如何處理檔案上傳的請求。

file upload

首先我們要介紹要如何在網頁應用程式上上傳檔案,這裡常用的技術是使用form POST的file類型,所以我們要先有一個可以上傳檔案的view,以及處理上傳檔案請求的handler,所以接下利用iris example來跟大家介紹iris上的處理。

iris 處理 file upload

首先要跟大家介紹的是view要怎麼設計才能上傳檔案呢,所以大家先看一下下列範例

<html>

<head>
	<title>Upload file</title>
</head>

<body>
	<form enctype="multipart/form-data" action="http://127.0.0.1:8080/upload" method="POST">
		<input type="file" name="uploadfile" />
		<input type="hidden" name="token" value="{{.}}" />
		<input type="submit" value="upload" />
	</form>
</body>

</html>

上面是一個簡單的上傳檔案的form,選擇檔案後按下submit就可以提交上傳檔案的請求,接下來再跟大家分享如何處理上傳檔案的請求。

    // Handle the post request from the upload_form.html to the server
    app.Post("/upload", iris.LimitRequestBodySize(maxSize+1<<20), func(ctx iris.Context) {
		// Get the file from the request.
		f, fh, err := ctx.FormFile("uploadfile")
		if err != nil {
			ctx.StatusCode(iris.StatusInternalServerError)
			ctx.HTML("Error while uploading: <b>" + err.Error() + "</b>")
			return
		}
		defer f.Close()

		_, err = ctx.SaveFormFile(fh, filepath.Join("./uploads", fh.Filename))
		if err != nil {
			ctx.StatusCode(iris.StatusInternalServerError)
			ctx.HTML("Error while uploading: <b>" + err.Error() + "</b>")
			return
		}
	})

	// start the server at http://localhost:8080 with post limit at 5 MB.
	app.Listen(":8080" /* 0.*/, iris.WithPostMaxMemory(maxSize))

上面例子中介紹如何處理上傳檔案的請求,有幾點要說明一下,首先是處理將請求收下來的動作,這裡使用ctx.FormFile(fileName string)將上傳的檔案儲存到記憶體空間,接下來透過
ctx.SaveFormFile(fh, filepath.Join("./uploads", fh.Filename))這方法將記憶體中的檔案儲存成實體檔案,這樣處理上傳檔案的請求就結束了,不過還有一點要注意一下,那就是記得要設定上傳檔案的最大值,不然遇到惡意的請求會把網頁伺服器的硬碟空間塞爆,所以這邊使用app.Listen(":8080" /* 0.*/, iris.WithPostMaxMemory(maxSize))來設定檔案最大值。

結論

今天跟大家介紹如何處理這個form POST的一個特殊應用file upload,所以iris處理使用者的請求講到這裡告一段落。


上一篇
iris 的 form post
下一篇
iris的model驗證
系列文
Iris這個在go語言上地表最快的網頁框架30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言