Fork me on GitHub

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

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 @ 2025-01-09 17:21  WantRemake  阅读(29)  评论(0)    收藏  举报