加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang 实现简单的文件上传

发布时间:2020-12-16 18:21:16 所属栏目:大数据 来源:网络整理
导读:示例代码: package mainimport ("fmt""io""net/http""os")const (upload_path string = "./upload/")func load_success(w http.ResponseWriter,r *http.Request) {io.WriteString(w,"上传成功!")}//上传func uploadHandle(w http.ResponseWriter,r *http.Re






示例代码:

package main

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

const (
	upload_path string = "./upload/"
)

func load_success(w http.ResponseWriter,r *http.Request) {
	io.WriteString(w,"上传成功!")

}

//上传
func uploadHandle(w http.ResponseWriter,r *http.Request) {
	//从请求当中判断方法
	if r.Method == "GET" {
		io.WriteString(w,"<html><head><title>上传</title></head>"+
			"<body><form action='#' method="post" enctype="multipart/form-data">"+
			"<label>上传图片</label>"+":"+
			"<input type="file" name='file'  /><br/><br/>"+
			"<label><input type="submit" value="上传图片"/></label></form></body></html>")
	} else {
		//获取文件内容 要这样获取
		file,head,err := r.FormFile("file")
		if err != nil {
			fmt.Println(err)
			return
		}
		defer file.Close()
		//创建文件
		fW,err := os.Create(upload_path + head.Filename)
		if err != nil {
			fmt.Println("文件创建失败")
			return
		}
		defer fW.Close()
		_,err = io.Copy(fW,file)
		if err != nil {
			fmt.Println("文件保存失败")
			return
		}
		//io.WriteString(w,head.Filename+" 保存成功")
		http.Redirect(w,r,"/success",http.StatusFound)
		//io.WriteString(w,head.Filename)
	}
}

func main() {
	fmt.Println("OK!")
	//启动一个http 服务器
	http.HandleFunc("/success",load_success)
	//上传
	http.HandleFunc("/upload",uploadHandle)
	err := http.ListenAndServe(":8080",nil)
	if err != nil {
		fmt.Println("服务器启动失败")
		return
	}
	fmt.Println("服务器启动成功")
}




和Java语言相比,go语言程序更加简洁、轻便;并发性好;良好的语言设计和拥有较好的执行性能。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读