• 如何传输文件流给前端


    通过链接下载图片,直接http请求然后将文件流返回
    注:music.ly是一个下载tiktok视频的免费接口 https://api19-core-c-useast1a.musical.ly/aweme/v1/feed/?aweme_id=xxx

    func (m *FileBiz) DownloadFileV2(ctx *ctrl.Context, fileLink, fileName string) (err error) {
    
    	// 记录下载日志
    	record.BusinessLog(record.Debug, "RecordDownloadFileV2", fmt.Sprintf("filePath:%s,wsId:%s,email:%s", fileLink, ctx.GetString("ws_id"), ctx.GetString("email")), "")
    
    	// 获取地址异常
    	if fileLink == "" {
    		err = errInfo.ErrFilesNull
    		return
    	}
    
    	// 初始化
    	request, err := http.NewRequest("GET", fileLink, nil)
    	if err != nil {
    		record.BusinessLog(record.Error, "NewRequest", fmt.Sprintf("filePath:%s", fileLink), err.Error())
    		err = errInfo.ErrHttpInit
    		return
    	}
    
    	// 执行请求
    	clt := http.Client{}
    	resp, err := clt.Do(request)
    	if err != nil {
    		record.BusinessLog(record.Error, "HttpDp", fmt.Sprintf("filePath:%s", fileLink), err.Error())
    		err = errInfo.ErrHttpDo
    		return
    	}
    
    	defer func(Body io.ReadCloser) {
    		errClose := Body.Close()
    		if errClose != nil {
    			record.BusinessLog(record.Error, "FileClose", fmt.Sprintf("filePath:%s", fileLink), errClose.Error())
    		}
    	}(resp.Body)
    
    	// 响应头
    	ctx.Header("Content-Length", resp.Header.Get("Content-Length"))
    	ctx.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", fileName))
    	ctx.Header("Content-Type", "application/octet-stream;charset=UTF-8")
    	ctx.Header("Set-Cookie", "download=success; Domain=.media.io; Path=/;")
    
    	// 响应流
    	written, err := io.Copy(ctx.ResponseWriter(), resp.Body)
    	if err != nil {
    		record.BusinessLog(record.Error, "IoCopy", fmt.Sprintf("filePath:%s, written:%d", fileLink, written), err.Error())
    		err = errInfo.ErrResponseWritten
    	}
    
    	return
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
  • 相关阅读:
    我的世界Bukkit服务器插件开发教程(十)实体
    是的你没看错,js生成word文档
    小程序学习 1
    【kafka】二、kafka安装
    actuator--基础--07--自定义Endpoint
    面试突击73:IoC 和 DI 有什么区别?
    机器学习股票大数据量化分析与预测系统 - python 计算机竞赛
    Document Object Model
    练[MRCTF2020]Ez_bypass
    【JavaScript】手撕前端面试题:手写new操作符 | 手写Object.freeze
  • 原文地址:https://blog.csdn.net/Mengbabe_2018/article/details/132782843