Golang仿云盘项目-2.3 实现文件下载、修改、删除接口

本文来自博客园,作者:Jayvee,转载请注明原文链接:https://www.cnblogs.com/cenjw/p/16462188.html

目录结构

❯ pwd
/home/cenjw/gowork/src/FileStorageDisk
❯ tree
.
├── handler
│   └── handler.go
├── main.go
├── meta
│   └── filemeta.go
├── README.md
├── static
│   └── view
│       └── index.html
└── util
    └── util.go

下载文件接口

1.编写下载文件接口:handler/handler.go

点击查看代码
// DownloadHandler: 下载文件接口
func DownloadHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	// 拿到客户端发送来的sha1值
	fsha1 := r.Form.Get("filehash")
	// 获取元信息对象
	fm := meta.GetFileMeta(fsha1)
	// 从指定位置读入文件到内存,然后返回给客户端
	f, err := os.Open(fm.Location)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	defer f.Close()

	// 加载到内存(文件较小时可使用ioutil一次性全部加载到内存;
	// 文件较大时应要考虑实现流的形式)
	data, err := ioutil.ReadAll(f)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	// 加上http的响应头,让浏览器识别出来,然后就可以当成一个文件的下载
	w.Header().Set("Content-Type", "application/octect-stream")
	w.Header().Set("content-disposition", "attachment;filename=\"" + fm.FileName + "\"")
	w.Write(data)
}

2.添加路由
main.go

func main() {
	...
	http.HandleFunc("/file/dowload", handler.DownloadHandler)
	...
}

3.验证
先上传一张名为boy.gif的图片
http://localhost:8080/file/upload
image
要提前计算好文件的sha1值(要通过这个值获取到“云端”的文件信息)

sha1sum boy.gif

查看图片的元信息
http://localhost:8080/file/meta?filehash=图片的sha1值
image
下载文件
http://localhost:8080/file/download?filehash=图片的sha1值
image

本文来自博客园,作者:Jayvee,转载请注明原文链接:https://www.cnblogs.com/cenjw/p/16462188.html

文件修改接口

1.文件修改接口编写:handler.handler.go

点击查看代码
// UpdateFileMetaHandler: 修改文件接口(重命名)
func UpdateFileMetaHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	// 3个参数:待操作类型、fsha1值、新文件名
	opType := r.Form.Get("op")  // 0 表示重命名操作
	fsha1 := r.Form.Get("filehash")
	newFilename := r.Form.Get("filename")

	// 暂时仅支持重名命操作
	if opType != "0" {
		w.WriteHeader(http.StatusForbidden)
		return
	}

	// POST 请求
	if r.Method != "POST" {
		w.WriteHeader(http.StatusMethodNotAllowed)
		return
	}

	// 修改当前文件名
	curFileMeta := meta.GetFileMeta(fsha1)
	curFileMeta.FileName = newFilename
	meta.UpdateFileMeta(curFileMeta)

	// 转成json字符串形式,返回给客户端
	data, err := json.Marshal(curFileMeta)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusOK)
	w.Write(data)
}

2.添加路由:main.go
3.验证

参数比较多,在Postman中更方便测试API

更新图片名:
image

已经成功修改:
image

删除文件接口

1.编写接口:handler/handler.go

点击查看代码
// DeleteFileHandler: 删除文件的接口
func DeleteFileHandler(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	fsha1 := r.Form.Get("filehash")
	fm := meta.GetFileMeta(fsha1)

	// 删除文件在"云端"的物理位置
	os.Remove(fm.Location)

	// 删除对应文件元信息的索引
	meta.RemoveFileMeta(fsha1)

	w.WriteHeader(http.StatusOK)
	io.WriteString(w, "Delete successfully!")
}

2.添加路由
3.验证
删除后,再查询,文件元信息已经没有了
image

posted on 2022-07-10 20:13  micromatrix  阅读(400)  评论(0编辑  收藏  举报

导航