用ASP.NET Core WebApi把ofd文件上传到服务器上处理为pdf文件后返回一个服务器地址

目录

[步骤 1: 创建 ASP.NET Core Web API 项目](#步骤 1: 创建 ASP.NET Core Web API 项目)

[步骤 2: 添加文件上传的 API 控制器](#步骤 2: 添加文件上传的 API 控制器)

[步骤 3: 配置 Startup.cs 或 Program.cs](#步骤 3: 配置 Startup.cs 或 Program.cs)

[步骤 4: 运行和测试 API](#步骤 4: 运行和测试 API)


步骤 1: 创建 ASP.NET Core Web API 项目

  1. 打开 Visual Studio(或 Visual Studio Code),选择"新建项目"。
  2. 选择"ASP.NET Core Web API"模板,点击"下一步"。
  3. 输入项目名称和位置,点击"创建"。
  4. 选择目标框架(如 .NET 6 或 .NET 7),然后点击"创建"。

步骤 2: 添加文件上传的 API 控制器

在生成的项目中,我们将创建一个 API 控制器来处理文件上传。文件将上传到服务器,在服务器上处理,并返回文件的存储地址。

在 Controllers 文件夹中,添加一个新类 FilesController.cs,然后添加以下代码:

cs 复制代码
using Aspose.Pdf.Facades;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Spire.Pdf.Conversion;
using System.Reflection.Metadata;

namespace OfdConvertToPdf.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FilesController : ControllerBase
    {
        private readonly IWebHostEnvironment _environment;

        public FilesController(IWebHostEnvironment environment)
        {
            _environment = environment;
        }

        [HttpPost("upload")]
        public async Task<IActionResult> UploadAndConvertToPdf(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return BadRequest("上传文件为空");
            }

            try
            {
                // 根据当前日期创建上传目录
                string dateFolder = DateTime.Now.ToString("yyyy-MM-dd"); // 格式:2024-08-28
                string uploadDir = Path.Combine(_environment.WebRootPath, "uploads", dateFolder);

                if (!Directory.Exists(uploadDir))
                {
                    Directory.CreateDirectory(uploadDir);
                }
                string uploadedFilePath = Path.Combine(uploadDir, file.FileName);

                // 保存上传的文件
                using (var stream = new FileStream(uploadedFilePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                DirectoryInfo directory = new DirectoryInfo(uploadDir);
                List<FileInfo> ofdFiles = GetFiles(directory, ".ofd");
                foreach (FileInfo fi in ofdFiles)
                {
                    OfdConverter converter = new OfdConverter(fi.FullName);

                    converter.ToPdf(fi.FullName.Replace(".ofd", ".pdf"));
 //低版本免费Sprie.PDF无法使用ofd转pdf,我这里用了10.2.0版本,下面注释代码针对低于10.2.0版本的Spire.PDF
                 //foreach (FileInfo pdf in pdfFiles)
                //{
                //    if (Path.GetFileNameWithoutExtension(fi.FullName) == Path.GetFileNameWithoutExtension(pdf.FullName))
                //    {
                //        //两种方式,这一种尝试Aspose.pdf 21.10.0版本抛出异常,降低版本9.7.0,采用了直接输入key的方式
                //        //string path = Path.Combine(_environment.WebRootPath, "license", "Aspose.Total.lic");
                //        //Aspose.Pdf.License license = new Aspose.Pdf.License();
                //        //license.SetLicense(path); 
                //        string Key = "有需要youchang找我要Aspose.Total.lic或者Key";

                //        Stream LStream = (Stream)new MemoryStream(Convert.FromBase64String(Key));
                //        new Aspose.Pdf.License().SetLicense(LStream);
                //        PdfContentEditor pdfContentEditor = new PdfContentEditor();
                //        pdfContentEditor.BindPdf(pdf.FullName);
                //        pdfContentEditor.ReplaceText("Evaluation Warning : The document was created with Spire.PDF for .NET.", "");
                //        pdfContentEditor.Save(pdf.FullName);
                //    }
                //}
                }
                // 删除原始文件(如果需要)
                if (System.IO.File.Exists(uploadedFilePath))
                {
                    System.IO.File.Delete(uploadedFilePath);
                }

                // 返回PDF文件访问的 URL
                string fileUrl = $"{Request.Scheme}://{Request.Host}/uploads/{dateFolder}/{Path.GetFileNameWithoutExtension(file.FileName) + ".pdf"}";
                return Ok(new { fileUrl });
            }
            catch (Exception ex)
            {
                return StatusCode(500, "文件处理失败: " + ex.Message);
            }
        }

        static List<FileInfo> GetFiles(DirectoryInfo folder, string fileExtension)
        {
            List<FileInfo> files = new List<FileInfo>();
            foreach (FileInfo fi in folder.EnumerateFiles())
            {
                if (fi.Extension.ToLower() == fileExtension)
                    files.Add(fi);
            }

            return files;
        }
    }
}

步骤 3: 配置 Startup.cs 或 Program.cs

确保项目配置正确以支持文件上传。对于 ASP.NET Core 6 或 7(最小化主机模型),我们需要在 Program.cs 中配置静态文件支持和请求限制。

在 Program.cs 中,确保包含以下配置:

cs 复制代码
var builder = WebApplication.CreateBuilder(args);

// 添加服务到容器
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// 配置中间件
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseStaticFiles(); // 支持静态文件以便访问上传的文件

app.UseAuthorization();

app.MapControllers();

app.Run();

步骤 4: 运行和测试 API

  1. 启动 API 项目。
  2. swagger直接测试或使用工具(如 Postman 或 curl)发送 POST 请求到 https://localhost:端口/api/files/upload(具体端口号以你项目配置为准)。
  3. 确保请求中包含一个 form-data 文件字段用于文件上传。

使用 Postman 进行测试

  • 设置请求类型为 POST。
  • 在 URL 中输入 https://localhost:端口/api/files/upload。
  • 选择 Body 选项卡,选择 form-data。
  • 添加一个新的 Key,选择 File 类型,然后选择一个要上传的文件。
相关推荐
weixin_404679312 小时前
cc 在 linux 安装
linux·运维·服务器
贞明电子4 小时前
贞明电子网口设备 Modbus TCP 工业接入实战指南
服务器·网络协议·tcp/ip·贞明电子
小宋10215 小时前
embedding 返回全零向量,索引却照收不误:入库前的向量健康门禁、隔离重算与召回恢复判据
linux·服务器·网络·人工智能
如夏倾城6 小时前
NGFW ( Next-Generation Firewall,下一代防火墙)
运维·服务器·网络·http·网络安全·ssl·信息与通信
无奈笑天下18 小时前
Linux上kdump故障标准处理流程
linux·运维·服务器·github
瑞雪兆丰年兮1 天前
Linux快速入门 第四章 Linux系统常用操作技巧
linux·运维·服务器
星恒随风1 天前
从0实现C++ AI大模型接入SDK(四):大模型API接入、公共数据结构设计与日志库封装
linux·服务器·数据结构·c++·人工智能
时间的拾荒人1 天前
Linux进程间通信(上篇):匿名管道 +进程池(基于匿名管道实现)
linux·服务器·管道
无足鸟ICT1 天前
【RHCA+】介绍proc
linux·运维·服务器
布莱克6051 天前
Swift 下标(Subscript)详解:从语法到实战
服务器·开发语言·ios·ssh·swift·下标