สร้างโปรเจ็กส์แบบ ASP.NET Core Web API
เพิ่ม API Controller ชื่อ Values (Controllers/ValuesController.cs
)
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace WebApi1.Controllers
{
[Route("[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly ILogger<ValuesController> _logger;
private IWebHostEnvironment _env;
public ValuesController(ILogger<ValuesController> logger
, IWebHostEnvironment env)
{
_logger = logger;
_env = env;
}
// GET api/<ValuesController>/5
[HttpGet("{id}")]
public string Get(int id)
{
string rootPath;
if (!string.IsNullOrEmpty(_env.WebRootPath))
rootPath = _env.WebRootPath;
else
rootPath = _env.ContentRootPath;
_logger.LogInformation($"rootPath = {rootPath}");
#region Convert byte[] to Base64String
string pdfPathIP = System.IO.Path.Combine(rootPath, "resource/testIP.pdf");
_logger.LogInformation($"pdfPathIP = {pdfPathIP}");
byte[] bytesIP = System.IO.File.ReadAllBytes(pdfPathIP);
string pdfBase64 = Convert.ToBase64String(bytesIP);
#endregion
#region Convert Base64String to byte[]
string pdfPathOP = System.IO.Path.Combine(rootPath, "resource/testOP.pdf");
_logger.LogInformation($"pdfPathOP = {pdfPathOP}");
byte[] bytesOP = Convert.FromBase64String(pdfBase64);
System.IO.File.WriteAllBytes(pdfPathOP, bytesOP);
#endregion
return pdfBase64;
}
}
}
วางไฟล์ทดสอบไว้ที่ resource/testIP.pdf
ทดลองเรียก https://localhost:7034/values/5
จะได้ไฟล์ resource/testOP.pdf