Fork me on GitHub

C#根据传入的id截图生成附件、根据id生成下载链接、根据链接下载附件

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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
using Microsoft.Ajax.Utilities;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PuppeteerSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Configuration;
using System.Web.Helpers;
using System.Web.Http;
using WXHRApi.Controllers.OtherHelper;
using WXHRApi.Models;
using WXHRApi.Models.ApprovalTask;
using WXHRApi.Models.CommonDto;
using WXHRApi.Models.CusTom;
 
namespace WXHRApi.Controllers
{
    [RoutePrefix("api/ApprovalTask")]
    public class ApprovalTaskController : ApiController
    {
         
        /// <summary>
        /// 根据传入的TaskId模拟导出表单截图为pdf
        /// </summary>
        /// <returns></returns>
        //[AcceptVerbs("GET", "POST")]
        //[Route("ExportAsPdfAsync")]
        //public async Task<ResponseResult> ExportAsPdfAsync(string taskId, string sn)
        //{
        //    ResponseResult resResult = new ResponseResult();
 
        //    // 1. 下载 Chromium(只需一次) 
        //    var browserFetcher = new BrowserFetcher();
        //    var installedBrowsers = browserFetcher.GetInstalledBrowsers();
 
        //    if (!installedBrowsers.Any())
        //    {
        //        // 如果没有已安装的浏览器,下载 Chromium
        //        await browserFetcher.DownloadAsync();
        //        LogHel.WriteLog("1.Chromium 下载完成");
        //    }
        //    else
        //    {
        //        LogHel.WriteLog("1.Chromium 已经存在,无需下载");
        //    }
 
        //    // 2. 启动浏览器 
        //    try
        //    {
        //        using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions
        //        {
        //            Headless = true, // 设置为无头模式(没有UI) 
        //            //ExecutablePath = chromePath,
        //            Args = new[] { "--no-sandbox", "--disable-setuid-sandbox" }
        //        }))
        //        {
        //            // 3. 打开新页面 
        //            using (var page = await browser.NewPageAsync())
        //            {
        //                var requestUrl = WebConfigurationManager.AppSettings["PDFBaseRequestUrl"];
        //                var account = WebConfigurationManager.AppSettings["BPMUser"];
        //                if (!string.IsNullOrEmpty(taskId))
        //                {
        //                    requestUrl = requestUrl + "?isnoLogin=true&tid=" + taskId;
        //                }
        //                // 4. 导航到指定页面 
        //                try
        //                {
        //                    await page.GoToAsync(requestUrl, new NavigationOptions { Timeout = 150000 });
        //                }
        //                catch (Exception ex)
        //                {
        //                    resResult.Code = 500;
        //                    resResult.Message = $"导航到页面失败,错误:{ex.Message}";
        //                    return resResult;
        //                }
 
        //                string fileId = PostProcess.GetNewFileID();
        //                if (string.IsNullOrEmpty(fileId))
        //                {
        //                    resResult.Code = 500;
        //                    resResult.Message = "附件ID获取失败!";
        //                }
 
        //                //获取文件保存完整路径
        //                string savePathRoot = WebConfigurationManager.AppSettings["AttachmentRootPath"];
 
        //                savePathRoot = PostProcess.FileIDToPath(fileId, savePathRoot);
 
        //                var dirPath = savePathRoot.Substring(0, savePathRoot.LastIndexOf(@"\"));
        //                if (!Directory.Exists(dirPath))
        //                    Directory.CreateDirectory(dirPath);
        //                AttachmentInfo attInfo = new AttachmentInfo()
        //                {
        //                    FileID = fileId,
        //                    Ext = ".pdf",
        //                    Name = sn + ".PDF",
        //                    LastUpdate = DateTime.Now,
        //                    OwnerAccount = account,
        //                    Size = 0,
        //                };
 
        //                resResult.Data = fileId;
        //                //延时一段时间,否则可能截图到空白页
        //                await Task.Delay(2000);
 
        //                // 5. 截图保存为图片 
        //                await page.PdfAsync($"{savePathRoot}");
        //                //6.保存附件信息
        //                string connectionString = Convert.ToString(WebConfigurationManager.ConnectionStrings["BPMDB"]);
        //                using (SqlConnection cn = new SqlConnection(connectionString))
        //                {
        //                    try
        //                    {
        //                        cn.Open();
        //                        PostProcess.Insert(cn, attInfo);
        //                    }
        //                    catch (SqlException e)
        //                    {
        //                        cn.Close();
        //                        resResult.Code = 500;
        //                        resResult.Message = $"附件信息插入失败,错误原因:{e.Message}";
        //                    }
        //                }
        //            }
 
        //            // 7. 关闭浏览器 
        //            await browser.CloseAsync();
 
        //            return resResult;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        resResult.Code = 500;
        //        resResult.Message = $"保存PDF异常,错误原因:{ex.Message},{ex.StackTrace}";
        //        return resResult;
        //    }
        //}
 
        /// <summary>
        /// 根据fileId生成下载文件地址
        /// </summary>
        /// <param name="fileID"></param>
        /// <returns></returns>
 
        [Route("DownLoadFileByID")]
        //[HttpPost]
        [AcceptVerbs("GET", "POST")]
        public HttpResponseMessage DownLoadFileByID(string fileID)
        {
            byte[] buffer;
            string attachmentRootPath = WebConfigurationManager.AppSettings["AttachmentRootPath"];
            string FilePath = Path.Combine(attachmentRootPath, AttachmentInfo.FileIDToPath(fileID));
            var obj = AttachmentHel.GetAttachmentInfo(fileID);
 
            string FileName = obj.Name;
            if (!File.Exists(FilePath))
                throw new Exception(string.Format(Resources.YZStrings.Aspx_Upload_FileIDNotFount, FileName));
            try
            {
 
 
                using (FileStream stream = new FileInfo(FilePath).OpenRead())
                {
                    buffer = new Byte[stream.Length];     //从流中读取字节块并将该数据写入给定缓冲区buffer中
                    stream.Read(buffer, 0, Convert.ToInt32(stream.Length));
                }
                HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
                httpResponseMessage.Content = new StreamContent(new MemoryStream(buffer));
                httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                var disPosition = new ContentDispositionHeaderValue("attachment");
                //IE等浏览器文件名中文乱码问题处理
                var userAgent = Request.Headers.UserAgent.ToString().ToUpper();
                if (userAgent.Contains("MSIE") || userAgent.Contains("TRIDENT") || userAgent.Contains("EDGE"))
                {
                    disPosition.FileName = System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);
                    //disPosition.Name = System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);
                    //disPosition.Size = (long)FileName.Length;
                }
                else
                {
                    disPosition.FileName = FileName;
                    //disPosition.Name = FileName;
                    //disPosition.Size = (long)FileName.Length;
                }
                httpResponseMessage.Content.Headers.ContentDisposition = disPosition;
 
               
                //httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                //{
                //    FileName = FileName,
                //};
                return httpResponseMessage;
            }
            catch (Exception)
            {
 
                return new HttpResponseMessage(HttpStatusCode.NoContent);
            }
        }
 
 
        /// <summary>
        /// 根据fileId下载文件
        /// </summary>
        /// <param name="fileID"></param>
        /// <returns></returns>
 
        [Route("SaveFileById")]
        //[HttpPost]
        [AcceptVerbs("GET", "POST")]
        public async Task SaveFileById(string fileID)
        {
            string url = $"http://xxx/api/ApprovalTask/DownLoadFileByID?fileID={fileID}";
            string saveDirectory = @"C:\xxx\"; // 替换为保存文件的路径和文件名
 
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 发送 GET 请求
                    HttpResponseMessage response = await client.GetAsync(url);
 
                    // 确保响应成功
                    response.EnsureSuccessStatusCode();
 
                    // 获取文件名
                    string fileName = GetFileNameFromResponse(response) ?? "default_file";
 
                    // 拼接完整保存路径
                    string saveFilePath = Path.Combine(saveDirectory, fileName);
 
                    // 读取内容为字节流
                    byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
 
                    // 保存到本地文件
                    File.WriteAllBytes(saveFilePath, fileBytes);
 
                    Console.WriteLine("文件保存成功:" + saveFilePath);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("下载文件失败:" + ex.Message);
            }
        }
 
        /// <summary>
        /// 获取文件名
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private static string GetFileNameFromResponse(HttpResponseMessage response)
        {
            if (response.Content.Headers.ContentDisposition != null)
            {
                return response.Content.Headers.ContentDisposition.FileName?.Trim('"');
            }
 
            if (response.Headers.TryGetValues("Content-Disposition", out var values))
            {
                string disposition = string.Join(";", values);
                var fileNameMarker = "filename=";
                int index = disposition.IndexOf(fileNameMarker, StringComparison.OrdinalIgnoreCase);
                if (index >= 0)
                {
                    int startIndex = index + fileNameMarker.Length;
                    int endIndex = disposition.IndexOf(';', startIndex);
                    if (endIndex < 0) endIndex = disposition.Length;
 
                    string encodedString = disposition.Substring(startIndex, endIndex - startIndex).Trim('"');
                    if (string.IsNullOrEmpty(encodedString))
                        return null;
 
                    //解码 MIME 编码的字符串
                    //匹配 MIME 编码格式:=?utf-8?B?...?=
                    var match = Regex.Match(encodedString, @"=\?utf-8\?B\?(?<encodedText>[A-Za-z0-9+/=]+)\?=", RegexOptions.IgnoreCase);
                    if (match.Success)
                    {
                        string base64EncodedText = match.Groups["encodedText"].Value;
                        byte[] bytes = Convert.FromBase64String(base64EncodedText);
                        return Encoding.UTF8.GetString(bytes);
                    }
 
                    return encodedString; // 如果不是 MIME 编码,直接返回原始字符串
                }
            }
 
            return null; // 如果无法获取文件名,返回 null
        }
    }
}

  

posted @   WantRemake  阅读(15)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示