用ASP.NET Core WebApi把ofd文件上传到服务器上处理为pdf文件后返回一个服务器地址
创始人
2024-09-25 11:22:55

目录

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

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

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

步骤 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,然后添加以下代码:

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 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 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 GetFiles(DirectoryInfo folder, string fileExtension)         {             List files = new List();             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 中,确保包含以下配置:

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 类型,然后选择一个要上传的文件。

相关内容

热门资讯

未来三年销售目标突破千亿元!京... 上证报中国证券网讯(记者 刘暄)京东与荣耀4月2日签署战略合作协议,明确未来三年荣耀在京东全渠道销售...
我国科研人员发现99个新物种 我国科研人员发现99个昆虫新物种 为青藏高原生物多样性再添新证 4月1日,我国科研人员在国际动物分类...
兴源自动化取得电芯高效测漏设备... 国家知识产权局信息显示,惠州市兴源自动化设备有限公司取得一项名为“一种电芯高效测漏设备”的专利,授权...
量旋科技完成6亿元C+轮融资 ... 本报讯 (记者张敏)4月3日,深圳量旋科技有限公司(以下简称“量旋科技”)宣布完成6亿元C+轮融资。...
李云泽:推动构建与未来产业全生... 上证报中国证券网讯 据金融监管总局4月3日消息,4月1日,金融监管总局举办党委理论学习中心组集体(扩...