網站首頁 編程語言 正文
本文實例為大家分享了Go實現文件上傳的具體代碼,供大家參考,具體內容如下
文件上傳:客戶端把上傳文件轉換為二進制流后發送給服務器,服務器對二進制流進行解析
HTML表單(form)enctype(Encode Type)屬性控制表單在提交數據到服務器時數據的編碼類型.
enctype=”application/x-www-form-urlencoded” 默認值,表單數據會被編碼為名稱/值形式
- enctype=”multipart/form-data” 編碼成消息,每個控件對應消息的一部分.請求方式必須是post
- enctype=”text/plain” 純文本形式進行編碼的
HTML模版內容如下(在項目/view/index.html)
<!DOCTYPE html>
<html lang="en">
<head>
? ? <meta charset="UTF-8">
? ? <title>文件上傳</title>
</head>
<body>
<form action="upload" enctype="multipart/form-data" method="post">
? ? 用戶名:<input type="text" name="username"/><br/>
? ? 密碼:<input type="file" name="photo"/><br/>
? ? <input type="submit" value="注冊"/>
</form>
</body>
</html>
服務端可以使用FormFIle(“name”)獲取上傳到的文件,官方定義如下
// FormFile returns the first file for the provided form key. // FormFile calls ParseMultipartForm and ParseForm if necessary. func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error) { ?? ?if r.MultipartForm == multipartByReader { ?? ??? ?return nil, nil, errors.New("http: multipart handled by MultipartReader") ?? ?} ?? ?if r.MultipartForm == nil { ?? ??? ?err := r.ParseMultipartForm(defaultMaxMemory) ?? ??? ?if err != nil { ?? ??? ??? ?return nil, nil, err ?? ??? ?} ?? ?} ?? ?if r.MultipartForm != nil && r.MultipartForm.File != nil { ?? ??? ?if fhs := r.MultipartForm.File[key]; len(fhs) > 0 { ?? ??? ??? ?f, err := fhs[0].Open() ?? ??? ??? ?return f, fhs[0], err ?? ??? ?} ?? ?} ?? ?return nil, nil, ErrMissingFile }
multipart.File是文件對象
// File is an interface to access the file part of a multipart message. // Its contents may be either stored in memory or on disk. // If stored on disk, the File's underlying concrete type will be an *os.File. type File interface { ?? ?io.Reader ?? ?io.ReaderAt ?? ?io.Seeker ?? ?io.Closer }
封裝了文件的基本信息
// A FileHeader describes a file part of a multipart request. type FileHeader struct { ?? ?Filename string?? ??? ??? ??? ??? ?//文件名 ?? ?Header ? textproto.MIMEHeader?? ?//MIME信息 ?? ?Size ? ? int64?? ??? ??? ??? ??? ?//文件大小,單位bit ?? ?content []byte?? ??? ??? ??? ??? ?//文件內容,類型[]byte ?? ?tmpfile string?? ??? ??? ??? ??? ?//臨時文件 }
服務器端編寫代碼如下
- 獲取客戶端傳遞后的文件流,把文件保存到服務器即可
package main import ( ? ?"net/http" ? ?"fmt" ? ?"html/template" ? ?"io/ioutil" ) /* 顯示歡迎頁upload.html ?*/ func welcome(rw http.ResponseWriter, r *http.Request) { ? ?t, _ := template.ParseFiles("template/html/upload.html") ? ?t.Execute(rw, nil) } /* 文件上傳 ?*/ func upload(rw http.ResponseWriter, r *http.Request) { ? ?//獲取普通表單數據 ? ?username := r.FormValue("username") ? ?fmt.Println(username) ? ?//獲取文件流,第三個返回值是錯誤對象 ? ?file, header, _ := r.FormFile("photo") ? ?//讀取文件流為[]byte ? ?b, _ := ioutil.ReadAll(file) ? ?//把文件保存到指定位置 ? ?ioutil.WriteFile("D:/new.png", b, 0777) ? ?//輸出上傳時文件名 ? ?fmt.Println("上傳文件名:", header.Filename) } func main() { ? ?server := http.Server{Addr: "localhost:8899"} ? ?http.HandleFunc("/", welcome) ? ?http.HandleFunc("/upload", upload) ? ?server.ListenAndServe() }
原文鏈接:https://blog.csdn.net/qq_27870421/article/details/118494346
相關推薦
- 2022-07-16 Linux中啟動Docker容器報錯:Error response from daemon: dri
- 2022-08-14 如何關閉Hyper-v虛擬服務_Hyper-V
- 2023-03-02 Flutter有狀態組件StatefulWidget生命周期詳解_Android
- 2022-09-26 Python文件相關操作和方法匯總大全_python
- 2023-07-25 mongodb本地連接失敗解決方案
- 2023-01-12 Python讀取mat(matlab數據文件)并實現畫圖_python
- 2023-07-16 uniapp 微信小程序導航功能(從地址列表內點擊某一個地址)
- 2024-02-01 啟動jar報錯(文件名、目錄名或卷標語法不正確。)
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支