前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go上传文件预览

go上传文件预览

作者头像
贵哥的编程之路
发布2024-03-14 09:02:47
660
发布2024-03-14 09:02:47
举报

helloworld/index.go:

代码语言:javascript
复制
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
			}
		//用于读取已上传文件的内容,返回文件的字节数据和可能的错误。
		data,err:=ioutil.ReadFile("./upload/" + handler.Filename)
			//表示返回的内容类型为纯文本
			w.Header().Set("Content-Type", "text/plain")
						//将读取的内容输出出来
						w.Write(data)
			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

代码语言:javascript
复制
<!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 就行了

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-03-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档