package main

import ( "fmt" "net/http" "os" )

func main() { http.HandleFunc("/", uploadFile) http.ListenAndServe(":8080", nil) }

func uploadFile(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { file, handler, err := r.FormFile("file") if err != nil { fmt.Println("Error Retrieving the File") fmt.Println(err) return } defer file.Close() fmt.Printf("Uploaded File: %+v\n", handler.Filename) fmt.Printf("File Size: %+v\n", handler.Size) fmt.Printf("MIME Header: %+v\n", handler.Header) // Create a new file dst, err := os.Create(handler.Filename) if err != nil { fmt.Println("Error Creating File") fmt.Println(err) return } defer dst.Close() // Copy the uploaded file to the destination file if _, err := io.Copy(dst, file); err != nil { fmt.Println("Error Copying File") fmt.Println(err) return } fmt.Fprintf(w, "Successfully Uploaded File\n") } else { fmt.Fprintf(w, "Invalid Request Method\n") } }

这是一个简单的上传文件的功能代码,使用了Go的标准库来处理HTTP请求和文件操作。当收到POST请求时,从请求中读取文件,然后将文件复制到一个新的文件中。如果一切顺利,则返回“成功上传文件”的消息,否则返回错误消息。

用go写一段上传文件的功能代码

原文地址: https://www.cveoy.top/t/topic/m0V 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录