日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

GO語言原生實現(xiàn)文件上傳功能_Golang

作者:Sirius_7 ? 更新時間: 2022-09-18 編程語言

本文實例為大家分享了GO原生實現(xiàn)文件上傳功能的具體代碼,供大家參考,具體內(nèi)容如下

寫在前面

最近在學(xué)習(xí)go,發(fā)現(xiàn)實踐才是檢驗真理的唯一標(biāo)準(zhǔn)。在不引入任何框架的基礎(chǔ)上,利用go語言實現(xiàn)一個web小應(yīng)用也是比較方便的,但是坑還是不少,這里直接放上來,以防以后自己用得到,也希望可以幫到你。

首先寫處理文件上傳的handler

package handler

/**
實現(xiàn)文件的上傳和下載
*/
import (
?? ?"fmt"
?? ?"io"
?? ?"io/ioutil"
?? ?"net/http"
?? ?"os"
)

//文件上傳(這里一定要注意,方法名首字母大寫,否則無法在別的包中被引用發(fā)現(xiàn))
func UploadHandler(w http.ResponseWriter, r *http.Request) {
?? ?//這里的輸出數(shù)字是為了等下等直觀的感受程序運行的過程,后面輸出的數(shù)字功能類似
?? ?fmt.Printf("4")
?? ?//首次訪問指定url默認(rèn)采用GET方法提交,所以需要調(diào)出提交文件表單頁面
?? ?if r.Method == "GET" {
?? ??? ?fmt.Printf("5")
?? ??? ?//通過讀取html文件再交由http.ResponseWriter輸出的方式實現(xiàn)文件提交頁面的喚出
?? ??? ?data, err := ioutil.ReadFile("static/view/index.html")
?? ??? ?if err != nil {
?? ??? ??? ?_, _ = io.WriteString(w, "something wrong!")
?? ??? ??? ?return
?? ??? ?}
?? ??? ?_, _ = io.WriteString(w, string(data))
?? ?} else if r.Method == "POST" {
?? ??? ?fmt.Printf("6")
?? ??? ?//將文件存儲至本地
?? ??? ?file, head, err := r.FormFile("file")

?? ??? ?if err != nil {
?? ??? ??? ?fmt.Printf("Failed to get file data %s\n", err.Error())
?? ??? ??? ?return
?? ??? ?}
?? ??? ?defer file.Close()
?? ??? ?//在本地創(chuàng)建一個新的文件去承載上傳的文件
?? ??? ?newFile, err := os.Create("/tmp/" + head.Filename)
?? ??? ?if err != nil {
?? ??? ??? ?fmt.Printf("Failed to create newFile data %s\n", err.Error())
?? ??? ??? ?return
?? ??? ?}

?? ??? ?defer newFile.Close()
?? ??? ?_, err = io.Copy(newFile, file)
?? ??? ?if err != nil {
?? ??? ??? ?fmt.Printf("Failed to save into newFile %s\n", err.Error())
?? ??? ??? ?return
?? ??? ?}
?? ??? ?// 重定向到成功的頁面邏輯
?? ??? ?http.Redirect(w, r, "/file/upload/suc", http.StatusFound)
?? ?}
}

// 文件上傳成功處理邏輯
func UploadSucHandler(w http.ResponseWriter, r *http.Request) {
?? ?_, _ = io.WriteString(w, "Upload Succeed!")
}

其次完成main方法,注冊路由信息

所謂的注冊路由信息,其實就是類似于java框架中配置url攔截規(guī)則,具體見下:

package main

import (
?? ?"log"
?? ?"net/http"
?? ?"zone/src/handler"
)

func main() {
?? ?//設(shè)置http的路由規(guī)則,類似于Java框架中設(shè)置請求攔截規(guī)則
?? ?http.HandleFunc("/file/upload", handler.UploadHandler)
?? ?http.HandleFunc("/file/upload/suc", handler.UploadSucHandler)
?? ?//開啟http監(jiān)聽
?? ?//err := http.ListenAndServe(":8080", nil)
?? ?//if err != nil {
?? ?//?? ?fmt.Printf("There is an err %s", err.Error())
?? ?//}
?? ?//上面方法不太優(yōu)雅,現(xiàn)在用log直接包裹監(jiān)聽
?? ?log.Fatal(http.ListenAndServe(":8081", nil))
}

最后完成前端文件提交頁面

<!DOCTYPE html>
<html lang="en">
<head>
? ? <meta charset="UTF-8">
? ? <title>上傳文件</title>
</head>
<body>
<form action="/file/upload" method="post" enctype="multipart/form-data">
? ? <p><input type="file" name="file" value=""></p>
? ? <p><input type="submit" value="submit"></p>
</form>
</body>
</html>

測試一下

程序后臺執(zhí)行情況:

原文鏈接:https://blog.csdn.net/weixin_38107316/article/details/111132385

欄目分類
最近更新