如何传输文件流给前端
通过链接下载图片,直接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.ErrFilesNullreturn}// 初始化request, err := http.NewRequest("GET", fileLink, nil)if err != nil {record.BusinessLog(record.Error, "NewRequest", fmt.Sprintf("filePath:%s", fileLink), err.Error())err = errInfo.ErrHttpInitreturn}// 执行请求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.ErrHttpDoreturn}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
}