Problem: You want to upload a file to a web application.
Solution: Use the net/http package to create a web application and the io package to read the file.
Uploading files is commonly done through HTML forms. You learned that HTML forms have an enctype attribute that specifies the format of the form data. By default, the enctype is set to application/x-www-form-urlencoded . This means that the form data is encoded as a query string. However, if you set the enctype to multipart/form-data , the form data will be encoded as a MIME message. This is the format you need to upload files.
Here’s an example. You will create a web application that allows users to upload a file. The web application will display the filename and the file size. The web application will also save the file to the local filesystem:
func main() { http.HandleFunc("/upload", upload) http.ListenAndServe(":8000", nil) } func upload(w http.ResponseWriter, r *http.Request) { file, fileHeader, err := r.FormFile("uploadfile") if err != nil { fmt.Println(err) return } defer file.Close() fmt.Fprintf(w, "%v", fileHeader.Header) f, err := os.OpenFile("./uploaded/"+fileHeader.Filename, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { fmt.Println(err) return } defer f.Close() io.Copy(f, file) }
The first thing you need to do is to get the file from the HTML form. You can do this using the FormFile method. The FormFile method takes the name of the file input element as its argument and returns two values and an error. The first value is the file, an io.ReadCloser , and the second value is the file metadata, a multipart.FileHeader .
Using the file header, get the filename and then create a new file. Then use the io.Copy function to copy the file from the io.ReadCloser to the new file.
To test this, use curl to post a file to the server form. The syntax for curl is to use the -F (form) option, which will add enctype="multipart/form-data" to the request. The argument to this option is a string with the name of the file form field ( uploadfile ), followed by = and then @ followed by the path to the file to upload:
$ curl -F "uploadfile=@lenna.png" http://localhost:8000/upload
Once you run this command, you should see a file lenna.png created in the .uploaded directory.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
2019-10-17 PyCharm - disable autosave