用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 类型,然后选择一个要上传的文件。
相关推荐
心勤则明12 分钟前
Netty配置SSL证书加密
服务器·https·ssl
IT良36 分钟前
while循环及简单案例
linux·服务器
码哝小鱼1 小时前
iptables限制网速
linux·服务器·网络
leaoleao沄1 小时前
linux-IO-进程-线程(相关函数)
linux·运维·服务器
iangyu1 小时前
linux命令之pwdx
linux·运维·服务器
C语言扫地僧2 小时前
Docker 镜像制作(Dockerfile)
linux·服务器·docker·容器
HPC_fac130520678162 小时前
RTX 4090 系列即将停产,RTX 5090 系列蓄势待发
服务器·人工智能·gpu算力
稳联技术2 小时前
汽车焊机数据通信:Profinet转Canopen网关的神奇连接
服务器·网络·汽车
钡铼技术物联网关2 小时前
Codesys 与 ARMxy ARM 工业控制器:工业控制的黄金组合
linux·运维·服务器·arm开发·硬件工程
Reuuse3 小时前
【HCIA-Datacom】华为VRP系统
服务器·网络·华为