前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Go语言之搭建文件下载服务端

Go语言之搭建文件下载服务端

原创
作者头像
IT工作者
发布2022-03-29 10:46:41
1.3K0
发布2022-03-29 10:46:41
举报
文章被收录于专栏:程序技术知识程序技术知识

一.文件下载简介

文件下载总体步骤

客户端向服务端发起请求,请求参数包含要下载文件的名称

服务器接收到客户端请求后把文件设置到响应对象中,响应给客户端浏览器

载时需要设置的响应头信息

Content-Type: 内容MIME类型

application/octet-stream 任意类型

Content-Disposition:客户端对内容的操作方式

inline 默认值,表示浏览器能解析就解析,不能解析下载

attachment;filename=下载时显示的文件名 ,客户端浏览器恒下载

二.代码

在view/index.html中

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <a href="download?filename=abc.png">下载</a>
</body>
</html>

在main.go中编写

代码语言:javascript
复制
package main

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

func showDownloadPage(rw http.ResponseWriter,r *http.Request){
   t,_:=template.ParseFiles("template/html/download.html")
   t.Execute(rw,nil)
}
func download(rw http.ResponseWriter,r *http.Request){
   //获取请求参数
   fn:=r.FormValue("filename")
   //设置响应头
   header:=rw.Header()
   header.Add("Content-Type","application/octet-stream")
   header.Add("Content-Disposition","attachment;filename="+fn)
   //使用ioutil包读取文件
   b,_:=ioutil.ReadFile("D:/"+fn)
   //写入到响应流中
   rw.Write(b)
}

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

   http.HandleFunc("/showdownload",showDownloadPage)
   http.HandleFunc("/download",download)

   server.ListenAndServe()
}

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

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

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