go上传文件

helloworld/index.go:

package main

import (
	"fmt"
	"io"
	"net/http"
	"os"
)
//写入响应.读取请求
func uploadFile(w http.ResponseWriter,r *http.Request){
	
	err:=r.ParseMultipartForm(10<<20)
	//10<<20代表二进制10左移动20位1010000000000000000000,转换为十进制就是 10485760字节。转换成mb的话,是10mb
	if err!=nil{//错误就输出错误信息
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return 
	}
	
	file,handler,err:=r.FormFile("file")//文件句柄 文件信息  可能发生的错误
	if err!=nil{//错误就输出错误信息
		http.Error(w,"error file",http.StatusBadRequest)
		return 
	}
	defer file.Close()

	dst, err := os.Create("./upload/" + handler.Filename)//保存到当前目录下的upload目录下.handler.Filename 表示从 HTTP 请求中获取的上传文件的原始文件名。
	if err != nil {//错误就输出错误信息
			http.Error(w, "创建文件错误", http.StatusInternalServerError)
			return
		}
		defer dst.Close()
		_,err=io.Copy(dst,file)//把file保存到dst变量中
			if err != nil {//错误就输出错误信息
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		
			fmt.Fprintf(w, "File uploaded successfully: %s", handler.Filename)//输出成功信息
		
		

}

func main() {

	// 创建一个文件服务器,用于提供静态文件
		fs := http.FileServer(http.Dir("static"))
		// 将文件服务器与根路径 "/" 关联起来
		http.Handle("/", fs)

	http.HandleFunc("/upload",uploadFile)
	http.ListenAndServe(":8080",nil)
}

static/index.html

<!DOCTYPE html>
<html lang="zh">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title></title>
</head>
<body>
	<form action="http://localhost:8080/upload" method="post" enctype="multipart/form-data">
	 文件上传:
	  <input type="file" name="file" id="file">
	  <input type="submit" value="Upload File" name="submit">
	</form>
</body>
</html>

目录结构:
在这里插入图片描述

运行:
http://localhost:8080/

cmd:
F:\gorun\src\HelloWorld>go run index.go
就行了

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

贵哥的编程之路(热爱分享)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值