Golang仿云盘项目-2.1 基础版文件上传

目录结构

E:\goproj\FileStorageDisk
│  main.go
│  readme.txt
│
├─handler
│      handler.go
│
└─static
    └─view
            index.html

上传一个文件
上传文件

本文来自博客园,作者:Jayvee,转载请注明原文链接:https://www.cnblogs.com/cenjw/p/2-1-upload-file.html

代码

main.go

点击查看代码
package main

import (
	"fileyunsys/handler"
	"fmt"
	"net/http"
)

func main() {
	http.HandleFunc("/file/upload", handler.UploadHandler)
	http.HandleFunc("/file/upload/ok", handler.UploadOkHandler)

	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		fmt.Printf("Failed to start the port, err:%s\n", err.Error())
		return
	}

}

handler/hander.go

点击查看代码
package handler

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

func UploadHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		// 返回文件上传页面
		data, err := ioutil.ReadFile("./static/view/index.html")
		if err != nil {
			fmt.Println("Internal server ereror")
			return
		}
		io.WriteString(w, string(data))

	} else if r.Method == "POST" {
		// 返回文件句柄、文件头信息、错误信息(如果有)
		file, head, err := r.FormFile("file")
		if err != nil {
			fmt.Printf("Failed to get data, err:%s\n", err.Error())
			return
		}
		defer file.Close()
		// 创建一个新文件来接收当前文件流
		newFile, err := os.Create("/tmp/" + head.Filename)
		if err != nil {
			fmt.Printf("Failed to create file, err:%s\n", err.Error())
			return
		}

		_, err = io.Copy(newFile, file)
		if err != nil {
			fmt.Printf("Failed to save the data to file, err:%s\n", err.Error())
			return
		}
		// 上传成功,重定向到一个成功页面
		http.Redirect(w, r, "/file/upload/ok", http.StatusFound)
	}
}

// UploadOkHandler: 上传成功页面
func UploadOkHandler(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "Upload successfully!")
}

index.html

posted on 2022-07-08 18:59  micromatrix  阅读(134)  评论(0编辑  收藏  举报

导航