浏览代码

公共文件下载

hsun 1 年之前
父节点
当前提交
a9a257dc4c
共有 1 个文件被更改,包括 22 次插入4 次删除
  1. 22 4
      controllers/resource.go

+ 22 - 4
controllers/resource.go

@@ -978,19 +978,37 @@ func (this *ResourceAuthController) FileDownload() {
 		return
 	}
 
+	// 生成本地文件
+	localFilePath := fmt.Sprintf("%s%s", utils.GetRandStringNoSpecialChar(6), fileName)
+	localFile, e := os.Create(localFilePath)
+	if e != nil {
+		br.Msg = "下载失败"
+		br.ErrMsg = "生成本地文件失败, Err: " + e.Error()
+		return
+	}
+	defer func() {
+		if e = localFile.Close(); e != nil {
+			fmt.Println("local file close err: ", e.Error())
+		}
+		if e = os.Remove(localFilePath); e != nil {
+			fmt.Println("local file remove err: ", e.Error())
+		}
+	}()
+
 	// 写入响应流
-	_, e = io.Copy(this.Ctx.ResponseWriter, down.Body)
+	//_, e = io.Copy(this.Ctx.ResponseWriter, down.Body)
+	_, e = io.Copy(localFile, down.Body)
 	if e != nil {
 		br.Msg = "下载失败"
 		br.ErrMsg = "复制文件资源失败, Err: " + e.Error()
 		return
 	}
-
 	// 设置响应头
-	this.Ctx.ResponseWriter.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName))
-	this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/octet-stream")
+	//this.Ctx.ResponseWriter.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName))
+	//this.Ctx.ResponseWriter.Header().Set("Content-Type", "application/octet-stream")
 
 	br.Ret = 200
 	br.Msg = "下载成功"
 	br.Success = true
+	this.Ctx.Output.Download(localFilePath, fileName)
 }