Iris 這個在 go 語言上地表最快的網頁框架-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處理使用者的請求講到這裡告一段落。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *