54 lines
1.8 KiB
C#
54 lines
1.8 KiB
C#
using Gather.Common.Util;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using System.IO;
|
|
|
|
namespace GatherAPI.Controllers.back
|
|
{
|
|
[Route("api/[controller]")]
|
|
[ApiController]
|
|
public class DownloadFileController : Controller
|
|
{
|
|
private readonly IWebHostEnvironment _webHostEnvironment;
|
|
|
|
public DownloadFileController(IWebHostEnvironment webHostEnvironment)
|
|
{
|
|
_webHostEnvironment = webHostEnvironment;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 下载文件接口
|
|
/// </summary>
|
|
/// <param name="Path">文件路径</param>
|
|
/// <returns></returns>
|
|
[Authorize]
|
|
[HttpGet]
|
|
public ActionResult Index(string Path)
|
|
{
|
|
try
|
|
{
|
|
if (string.IsNullOrEmpty(Path))
|
|
{
|
|
return Json(Tool.GetJsonWithCode(APICode.Fail, "路径不能为空"));
|
|
}
|
|
string web_path = _webHostEnvironment.WebRootPath;
|
|
var filePath = web_path + "/" + Path;
|
|
//以字符流的形式下载文件
|
|
FileStream fs = new FileStream(filePath, System.IO.FileMode.Open);
|
|
byte[] bytes = new byte[(int)fs.Length];
|
|
fs.Read(bytes, 0, bytes.Length);
|
|
fs.Close();
|
|
string displayName = System.IO.Path.GetFileName(filePath);
|
|
return File(bytes, "application/octet-stream", displayName);
|
|
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Util.LogHelper.WriteLog(ex.Message + ",行号:" + ex.StackTrace);
|
|
return Json(Tool.GetJsonWithCode(APICode.Fail, "发生错误,请联系管理员。"));
|
|
}
|
|
}
|
|
}
|
|
}
|