前端实现文件上传功能讲解 golang文件上传需要前端吗

大家好你们好!在本教程中,我们将构建一个非常简单的文件上传 HTTP 服务器,它允许您将文件上传到运行 Go 应用程序的服务器 。
您想要这样做的原因有无数种,您可以上传 CSV 报告以在复杂的财务系统中进行进一步处理,或者您可以创建一个很酷的图像处理应用程序,允许您修改您想要的任何照片的各个方面上传 。
值得庆幸的是 , 在 Go 中处理图像上传的任务相当简单,再加上TempFileGo 1.11 版中引入的新API , 我们可以相当快地提出一个非常优雅的系统!
步骤我们将从使用该net/http 包创建一个非常简单的 HTTP 服务器开始 。这将仅具有一个单独的端点,它将成为我们的 /upload端点 。
// main.gopackage mainimport ("net/http""fmt")func uploadFile(w http.ResponseWriter, r *http.Request) {fmt.Fprintf(w, "Uploading File")}func setupRoutes() {http.HandleFunc("/upload", uploadFile)http.ListenAndServe(":8080", nil)}func main() {fmt.Println("hello World")}如果我们想运行它 , 我们可以通过运行来实现go run main.go,如果我们没有犯任何错误,我们应该看到我们的服务器启动成功 。
好的 , 现在我们有了一个可以构建的基?。?让我们开始实现我们的上传端点来处理文件上传 。
package mainimport ("fmt""io/ioutil""net/http")func uploadFile(w http.ResponseWriter, r *http.Request) {fmt.Println("File Upload Endpoint Hit")// Parse our multipart form, 10 << 20 specifies a maximum// upload of 10 MB files.r.ParseMultipartForm(10 << 20)// FormFile returns the first file for the given key `myFile`// it also returns the FileHeader so we can get the Filename,// the Header and the size of the filefile, handler, err := r.FormFile("myFile")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 temporary file within our temp-images directory that follows// a particular naming patterntempFile, err := ioutil.TempFile("temp-images", "upload-*.png")if err != nil {fmt.Println(err)}defer tempFile.Close()// read all of the contents of our uploaded file into a// byte arrayfileBytes, err := ioutil.ReadAll(file)if err != nil {fmt.Println(err)}// write this byte array to our temporary filetempFile.Write(fileBytes)// return that we have successfully uploaded our file!fmt.Fprintf(w, "Successfully Uploaded File\n")}func setupRoutes() {http.HandleFunc("/upload", uploadFile)http.ListenAndServe(":8080", nil)}func main() {fmt.Println("Hello World")setupRoutes()}太棒了 , 我们可以尝试运行它,并通过go run main.go在我们的终端中再次调用来查看其他一切是否正常 。
前端我们需要一个非常简单的 HTML 前端来充当我们上传文件的门户 。我们不会打扰任何更复杂的方面,例如身份验证和用户管理 , 我们将只创建一个非常简单的form 元素,它允许我们从本地机器中选择一个文件并访问我们上面定义的 API 端点!
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta http-equiv="X-UA-Compatible" content="ie=edge" /><title>Document</title></head><body><formenctype="multipart/form-data"action="http://localhost:8080/upload"method="post"><input type="file" name="myFile" /><input type="submit" value="http://www.wokk.cn/upload" /></form></body></html>太棒了,我们现在可以测试我们所做的工作并且它成功上传了我们的文件!
尝试index.html在浏览器中打开此文件 , 然后尝试将文件上传到我们正在运行的 Web 服务器 。


以上关于本文的内容,仅作参考!温馨提示:如遇健康、疾病相关的问题,请您及时就医或请专业人士给予相关指导!

「四川龙网」www.sichuanlong.com小编还为您精选了以下内容,希望对您有所帮助: