Go文件函数_上传

服务器

1.从表单获取数据 r.FormFile("name")       <input type="file" name="file">

2.读取表单数据至内存中data, err := ioutil.ReadAll(file)   (ioutil包流式读写)   (php是$_FILES)

3.获取get请求的参数    fn := p.ByName("vid-id")        html中:action="http://127.0.0.1:9000/upload/2"

4.写入到服务器硬盘中  err = ioutil.WriteFile(VIDEO_DIR + fn, data, 0777)    (PHP是move_uploadfile_to)

5.返回结果给客户端w.WriteHeader(http.StatusCreated)    io.WriteString(w, "Uploaded successfully")

func uploadHandler(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
	// 能够读取到的最大的缓冲区内容
	r.Body = http.MaxBytesReader(w, r.Body, MAX_UPLOAD_SIZE)
	// ParseMultipartForm表单的最大
	if err := r.ParseMultipartForm(MAX_UPLOAD_SIZE); err != nil {
		sendErrorResponse(w, http.StatusBadRequest, "File is too big")
		return 
	}

	// 从表单拿到文件
	// file对应表单的name
	// 第二个是类型
	file, _, err := r.FormFile("file")
	if err != nil {
		log.Printf("Error when try to get file: %v", err)
		sendErrorResponse(w, http.StatusInternalServerError, "Internal Error")
		return 
	}

	// 读取到我们数据里面 
	data, err := ioutil.ReadAll(file)
	if err != nil {
		log.Printf("Read file error: %v", err)
		sendErrorResponse(w, http.StatusInternalServerError, "Internal Error")
	}

	// 获取文件名
	fn := p.ByName("vid-id")
	// 保存文件
	err = ioutil.WriteFile(VIDEO_DIR + fn, data, 0777)
	if err != nil {
		log.Printf("Write file error: %v", err)
		sendErrorResponse(w, http.StatusInternalServerError, "Internal Error")
		return
	}

	// 反馈code与信息
	w.WriteHeader(http.StatusCreated)
	io.WriteString(w, "Uploaded successfully")
}

表单

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>上传</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />
    <script src="main.js"></script>
</head>
<body>
    <form enctype="multipart/form-data" action="http://127.0.0.1:9000/upload/2" method="post">
        {{/*1.file input*/}}
        <input type="file" name="file">

        {{/*2.submit button*/}}
        <input type="submit" value="uplad file">
    </form>
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值