string pdfPath = System.IO.Path.Combine(savePath, fileName);
string pdfStr = JsonUtils.GetValue("pdfStr", item);
byte[] pdfBytes = Convert.FromBase64String(pdfStr);
File.WriteAllBytes(pdfPath, pdfBytes);
下载pdf文件:
/// <summary>
/// 下载pdf文件
/// </summary>
/// <param name="requestParams"></param>
/// <param name="url"></param>
/// <param name="cookies"></param>
/// <param name="pdfPath"></param>
/// <returns></returns>
private static ReturnValue<string> downloadPDF(Dictionary<string,object> requestParams,string url,string cookies,string pdfPath)
{
ReturnValue<string> rs_pdf = new ReturnValue<string>();
// 设置要下载的PDF文件的URL
// 创建一个 HttpClient 实例,并配置 CookieContainer 以管理 Cookies
var cookieContainer = new CookieContainer();
var handler = new HttpClientHandler
{
CookieContainer = cookieContainer,
UseCookies = true
};
var rs_ck = CookieChangeTools.GetCookieCollectionFromXQYCookieString(cookies);
using (HttpClient httpClient = new HttpClient(handler))
{
cookieContainer.Add(rs_ck.Value);
// 使用 Newtonsoft.Json 库将参数对象转换为 JSON 字符串
string jsonParams = Newtonsoft.Json.JsonConvert.SerializeObject(requestParams);
// 创建 HTTP 请求的内容
var content = new StringContent(jsonParams, System.Text.Encoding.UTF8, "application/json");
try
{
// 使用 Task.Run 在后台线程执行下载操作
Task.Run(async () =>
{
// 发送 POST 请求,传递参数
HttpResponseMessage response = await httpClient.PostAsync(url, content);
// 检查响应是否成功
if (response.IsSuccessStatusCode)
{
// 读取响应内容作为字节数组
byte[] pdfBytes = await response.Content.ReadAsByteArrayAsync();
System.IO.File.WriteAllBytes(pdfPath, pdfBytes);
rs_pdf.Value = pdfPath;
rs_pdf.Success = true;
}
else
{
rs_pdf.Success = false;
rs_pdf.Msg = "下载PDF文件时发生错误,HTTP 状态码:" + response.StatusCode;
}
}).Wait(); // 等待后台任务完成
}
catch (Exception ex)
{
rs_pdf.Success = false;
rs_pdf.Msg = "下载PDF文件时出错:" + XqdClass.Tools.GetExceptionMsg(ex);
}
}
return rs_pdf;
}