实现一个简单的页面上传文件功能。

    1. /**
    2. * MyFileUpload01
    3. * @Author: Jian Junbo
    4. * @Email: junbojian@qq.com
    5. * @Create: 2017/9/17 15:14
    6. * Copyright (c) 2017 Jian Junbo All rights reserved.
    7. *
    8. * Description: 简单的上传文件
    9. */
    10. package main
    11. import (
    12. "net/http"
    13. "fmt"
    14. "os"
    15. "io"
    16. "time"
    17. "path"
    18. "strconv"
    19. )
    20. func main() {
    21. http.HandleFunc("/", index)
    22. http.HandleFunc("/upload2", upload)
    23. err := http.ListenAndServe(":7373", nil)
    24. if err != nil{
    25. fmt.Println("服务器启动失败",err.Error())
    26. return
    27. }
    28. }
    29. func upload(writer http.ResponseWriter, request *http.Request) {
    30. request.ParseMultipartForm(32<<20)
    31. //接收客户端传来的文件 uploadfile 与客户端保持一致
    32. file, handler, err := request.FormFile("uploadfile")
    33. if err != nil{
    34. fmt.Println(err)
    35. return
    36. }
    37. defer file.Close()
    38. //上传的文件保存在ppp路径下
    39. ext := path.Ext(handler.Filename) //获取文件后缀
    40. fileNewName := string(time.Now().Format("20060102150405"))+strconv.Itoa(time.Now().Nanosecond())+ext
    41. f, err := os.OpenFile("./ppp/"+fileNewName, os.O_WRONLY|os.O_CREATE, 0666)
    42. if err != nil{
    43. fmt.Println(err)
    44. return
    45. }
    46. defer f.Close()
    47. io.Copy(f, file)
    48. fmt.Fprintln(writer, "upload ok!"+fileNewName)
    49. }
    50. func index(writer http.ResponseWriter, request *http.Request) {
    51. writer.Write([]byte(tpl))
    52. }
    53. const tpl = `<html>
    54. <head>
    55. <title>上传文件</title>
    56. </head>
    57. <body>
    58. <form enctype="multipart/form-data" action="/upload2" method="post">
    59. <input type="file" name="uploadfile">
    60. <input type="hidden" name="token" value="{...{.}...}">
    61. <input type="submit" value="upload">
    62. </form>
    63. </body>
    64. </html>`

    golang 上传文件(Web版) - 图1