irc-netcore-api/IRaCIS.Core.Application/Service/MinimalApiService/FileToPDFService.cs

138 lines
4.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using IRaCIS.Core.Application.Helper;
using MassTransit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using RestSharp;
using SharpCompress.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IRaCIS.Core.Application.Service.MinimalApiService
{
/// <summary>
/// 上传文件转PDF 或者给url 这边下载然后转PDF
///
/// </summary>
/// <param name="_hostEnvironment"></param>
[ApiExplorerSettings(GroupName = "Institution")]
public class FileToPDFService(IWebHostEnvironment _hostEnvironment) : ServiceBase
{
[AllowAnonymous]
[RoutePattern(HttpMethod = "Post")]
public async Task<IResult> UploadFileAsync([FromForm] IFormFile file)
{
var tempFileName = NewId.NextGuid() + file.FileName;
var tempPDFName = Path.GetFileNameWithoutExtension(tempFileName) + ".pdf";
// 获取wwwroot目录
var wwwRootPath = Path.Combine(FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment), "temp");
// 检查wwwroot/temp目录是否存在不存在则创建
if (!Directory.Exists(wwwRootPath))
{
Directory.CreateDirectory(wwwRootPath);
}
// 文件保存路径
var pdfFilePath = Path.Combine(wwwRootPath, tempPDFName);
var tempFilePath = Path.Combine(wwwRootPath, tempFileName);
using var stream = File.OpenWrite(tempFilePath);
await file.CopyToAsync(stream);
FileConvertHelper.ConvertWordToPdf(tempFilePath, Path.GetDirectoryName(pdfFilePath));
var fileBytes = await File.ReadAllBytesAsync(pdfFilePath);
// 清理临时上传的文件和pdf
if (File.Exists(pdfFilePath))
{
File.Delete(pdfFilePath);
}
if (File.Exists(tempFilePath))
{
File.Delete(tempFilePath);
}
new FileExtensionContentTypeProvider().Mappings.TryGetValue(Path.GetExtension(tempPDFName), out var contentType);
return Results.File(fileBytes, contentType);
}
public async Task<IResult> GetPDFFileAsync(string fileUrl)
{
var tempFileName = NewId.NextGuid() + Path.GetFileName(fileUrl);
var tempPDFName = Path.GetFileNameWithoutExtension(tempFileName) + ".pdf";
// 获取wwwroot目录
var wwwRootPath = Path.Combine(FileStoreHelper.GetIRaCISRootDataFolder(_hostEnvironment), "temp");
// 检查wwwroot/temp目录是否存在不存在则创建
if (!Directory.Exists(wwwRootPath))
{
Directory.CreateDirectory(wwwRootPath);
}
// 文件保存路径
var pdfFilePath = Path.Combine(wwwRootPath, tempPDFName);
var tempFilePath = Path.Combine(wwwRootPath, tempFileName);
//请求url获取文件
var client = new RestClient(fileUrl);
var request = new RestRequest(fileUrl, Method.Get);
var response = await client.ExecuteAsync(request);
// 检查响应是否成功
if (response.IsSuccessful)
{
// 将响应内容写入到本地文件
await File.WriteAllBytesAsync(tempFilePath, response.RawBytes);
FileConvertHelper.ConvertWordToPdf(tempFilePath, Path.GetDirectoryName(pdfFilePath));
var fileBytes = await File.ReadAllBytesAsync(pdfFilePath);
// 清理临时上传的文件和pdf
if (File.Exists(pdfFilePath))
{
File.Delete(pdfFilePath);
}
if (File.Exists(tempFilePath))
{
File.Delete(tempFilePath);
}
new FileExtensionContentTypeProvider().Mappings.TryGetValue(Path.GetExtension(tempPDFName), out var contentType);
return Results.File(fileBytes, contentType);
}
else
{
Console.WriteLine($"下载文件失败: {response.ErrorMessage}");
return Results.Problem("下载文件失败", statusCode: StatusCodes.Status500InternalServerError);
}
}
}
}