用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.csProgram.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 类型,然后选择一个要上传的文件。
相关推荐
努力努力再努力wz14 分钟前
【Linux进阶系列】:线程(下)
linux·运维·服务器·c语言·数据结构·c++·算法
todoitbo28 分钟前
使用n8n搭建服务器监控系统:从Webhook到Telegram告警的完整实现
运维·服务器·数据库·ai·向量数据库·流处理·n8n
全栈小542 分钟前
【C#】从一次异步锁逐渐展开浅谈服务器架构解决重复编码问题,我与AI的一次深度讨论得出的一些解决方案
服务器·架构·c#
weixin_537765801 小时前
【负载均衡】LVS原理与配置
服务器·负载均衡·lvs
我什么都学不会1 小时前
DNS主从服务器练习
linux·运维·服务器
zt1985q1 小时前
外网访问项目研发管理软件 codes
运维·服务器·windows·网络协议·tcp/ip
华纳云IDC服务商1 小时前
DNS记录更新后为什么还是访问不到新服务器?
运维·服务器
2501_930707781 小时前
使用C#代码在 PDF 中创建目录
pdf
涛声依旧393162 小时前
安装部署自己的nginx
运维·服务器·nginx
wanhengidc2 小时前
物理服务器都有哪些作用?
运维·服务器·安全·智能手机·云计算