栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

Go语言文件上传

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Go语言文件上传

一.文件上传
  • 文件上传:客户端把上传文件转换为二进制流后发送给服务器,服务器对二进制流进行解析
  • HTML表单(form)enctype(Encode Type)属性控制表单在提交数据到服务器时数据的编码类型.
  • enctype=”application/x-www-form-urlencoded” 默认值,表单数据会被编码为名称/值形式
    • enctype=”multipart/form-data” 编码成消息,每个控件对应消息的一部分.请求方式必须是post
    • enctype=”text/plain” 纯文本形式进行编码的
  • HTML模版内容如下(在项目/view/index.html)



    
    文件上传


用户名:
密码:
  • 服务端可以使用FormFIle(“name”)获取上传到的文件,官方定义如下
// FormFile returns the first file for the provided form key.
// FormFile calls ParseMultipartForm and ParseForm if necessary.
func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error) {
	if r.MultipartForm == multipartByReader {
		return nil, nil, errors.New("http: multipart handled by MultipartReader")
	}
	if r.MultipartForm == nil {
		err := r.ParseMultipartForm(defaultMaxMemory)
		if err != nil {
			return nil, nil, err
		}
	}
	if r.MultipartForm != nil && r.MultipartForm.File != nil {
		if fhs := r.MultipartForm.File[key]; len(fhs) > 0 {
			f, err := fhs[0].Open()
			return f, fhs[0], err
		}
	}
	return nil, nil, ErrMissingFile
}
  • multipart.File是文件对象
// File is an interface to access the file part of a multipart message.
// Its contents may be either stored in memory or on disk.
// If stored on disk, the File's underlying concrete type will be an *os.File.
type File interface {
	io.Reader
	io.ReaderAt
	io.Seeker
	io.Closer
}
  • 封装了文件的基本信息
// A FileHeader describes a file part of a multipart request.
type FileHeader struct {
	Filename string					//文件名
	Header   textproto.MIMEHeader	//MIME信息
	Size     int64					//文件大小,单位bit

	content []byte					//文件内容,类型[]byte
	tmpfile string					//临时文件
}
  • 服务器端编写代码如下
    • 获取客户端传递后的文件流,把文件保存到服务器即可
package main

import (
   "net/http"
   "fmt"
   "html/template"
   "io/ioutil"
)


func welcome(rw http.ResponseWriter, r *http.Request) {
   t, _ := template.ParseFiles("template/html/upload.html")
   t.Execute(rw, nil)
}


func upload(rw http.ResponseWriter, r *http.Request) {
   //获取普通表单数据
   username := r.FormValue("username")
   fmt.Println(username)
   //获取文件流,第三个返回值是错误对象
   file, header, _ := r.FormFile("photo")
   //读取文件流为[]byte
   b, _ := ioutil.ReadAll(file)
   //把文件保存到指定位置
   ioutil.WriteFile("D:/new.png", b, 0777)
   //输出上传时文件名
   fmt.Println("上传文件名:", header.Filename)
}

func main() {
   server := http.Server{Addr: "localhost:8899"}

   http.HandleFunc("/", welcome)
   http.HandleFunc("/upload", upload)

   server.ListenAndServe()
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/903853.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号