• 如何传输文件流给前端


    通过链接下载图片,直接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
  • 相关阅读:
    crypto:丢失的MD5
    汇编语言之栈
    10 个你必须要知道的重要JavaScript 数组方法
    第七章 查找 十、散列查找
    机器学习1
    Elasticsearch 从入门到实践
    用 Java?就用国产生态型应用开发框架:Solon v1.10.2
    翻阅必备----Java窗口组件,容器,布局,监听,事件 API大全
    CPT205-Computer Graphics
    【jQuery】jQuery中如何发送ajax请求以及解决跨域问题_10
  • 原文地址:https://blog.csdn.net/Mengbabe_2018/article/details/132782843