1
chenyong
4 天以前 b095c75267297527116cda105669015babc01972
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
using Microsoft.AspNetCore.Mvc;
using System.Text;
 
namespace WIDESEA_WMSServer.Controllers.System
{
    [Route("api/[controller]")]
    [ApiController]
    public class Sys_LogController : Controller
    {
        [HttpPost, Route("GetLogName"), AllowAnonymous]
        public WebResponseContent GetLogName()
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                List<object> data = new List<object>();
                DirectoryInfo folder = new DirectoryInfo(AppContext.BaseDirectory + "\\Logs\\");
                DirectoryInfo[] firstDirectoryInfos = folder.GetDirectories().OrderByDescending(x => x.CreationTime).ToArray();
                int k = 2020;
                for (int i = 0; i < firstDirectoryInfos.Length; i++)
                {
                    if (firstDirectoryInfos[i].Name != "Info")
                    {
                        FileInfo[] nextFileInfos = firstDirectoryInfos[i].GetFiles();
                        List<object> values = new List<object>();
                        for (int j = 0; j < nextFileInfos.Length; j++)
                        {
                            values.Add(new { label = nextFileInfos[j].Name, id = k, hidden = true, fatherNode = firstDirectoryInfos[i].Name });
                            k++;
                        }
                        data.Add(new { label = firstDirectoryInfos[i].Name, children = values, id = i, hidden = false });
                    }
                }
 
                return WebResponseContent.Instance.OK(data: data);
            }
            catch (Exception ex)
            {
                return WebResponseContent.Instance.Error(ex.Message);
            }
        }
 
        [HttpPost, Route("GetLog"), AllowAnonymous]
        public WebResponseContent GetLog(string fileName)
        {
            WebResponseContent content = new WebResponseContent();
            try
            {
                List<FileInfo> files = new List<FileInfo>();
                DirectoryInfo folder = new DirectoryInfo(AppContext.BaseDirectory + "\\Logs\\");
                DirectoryInfo[] firstDirectoryInfos = folder.GetDirectories();
                for (int i = 0; i < firstDirectoryInfos.Length; i++)
                {
                    FileInfo[] nextFileInfos = firstDirectoryInfos[i].GetFiles();
                    files.AddRange(nextFileInfos);
                }
                if (files.Count > 0)
                {
                    FileInfo file = files.Where(x => x.Name == fileName).FirstOrDefault();
                    using StreamReader stream = new StreamReader(file.FullName);
                    StringBuilder text = new StringBuilder();
                    List<string> lines = new List<string>();
                    int i = 0;
                    while (stream.Peek() >= 0)
                    {
                        var line = stream.ReadLine();
                        lines.Add(line);
                    }
 
                    content = WebResponseContent.Instance.OK(data: lines);
                }
                else
                {
                    content = WebResponseContent.Instance.Error($"未找到日志文件,【{fileName}】");
                }
            }
            catch (Exception ex)
            {
                content = WebResponseContent.Instance.Error($"打开日志文件错误,{ex.Message}");
            }
            return content;
        }
        [HttpPost, HttpGet, Route("DownLoadLog"), AllowAnonymous]
        public virtual ActionResult DownLoadLog(string fileName)
        {
            try
            {
                // 1. 参数验证
                if (string.IsNullOrWhiteSpace(fileName))
                {
                    return BadRequest("文件名不能为空");
                }
 
                string logDirectory = Path.Combine(AppContext.BaseDirectory, "Logs");
 
                if (!Directory.Exists(logDirectory))
                {
                    Directory.CreateDirectory(logDirectory);
                }
 
                string filePath = Path.Combine(logDirectory, fileName);
 
                if (Directory.Exists(filePath))
                {
                    return NotFound($"文件 {fileName} 不存在");
                }
 
                string extension = Path.GetExtension(fileName).ToLowerInvariant();
                if (!IsAllowedFileType(extension))
                {
                    return BadRequest($"不支持的文件类型: {extension}");
                }
 
                FileInfo fileInfo = new FileInfo(filePath);
 
                if (fileInfo.Length > 50 * 1024 * 1024) // 50MB限制
                {
                    return BadRequest("文件过大,无法下载");
                }
 
                byte[] fileBytes;
                using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        fileStream.CopyTo(memoryStream);
                        fileBytes = memoryStream.ToArray();
                    }
                }
 
                string contentType = GetContentType(extension);
 
                return File(fileBytes, contentType, fileName);
            }
            catch (UnauthorizedAccessException)
            {
                return StatusCode(403, "没有访问该文件的权限");
            }
            catch (PathTooLongException)
            {
                return BadRequest("文件路径过长");
            }
            catch (IOException ex)
            {
                return StatusCode(500, "文件读取失败,可能正在被其他进程使用");
            }
            catch (Exception ex)
            {
                return StatusCode(500, $"服务器内部错误: {ex.Message}");
            }
        }
        private bool IsAllowedFileType(string extension)
        {
            var allowedTypes = new[] { ".txt", ".log", ".csv", ".json", ".xml" };
            return allowedTypes.Contains(extension);
        }
 
        private string GetContentType(string extension)
        {
            return extension.ToLowerInvariant() switch
            {
                ".txt" => "text/plain; charset=utf-8",
                ".log" => "text/plain; charset=utf-8",
                ".csv" => "text/csv; charset=utf-8",
                ".json" => "application/json; charset=utf-8",
                ".xml" => "application/xml; charset=utf-8",
                _ => "application/octet-stream"
            };
        }
    }
}