Microsoft .NET/ASP.Net & ASP.Net Core

[ASP.Net Core API] File Upload API / 파일 업로드 API

전자기린 2021. 2. 3. 11:23

파일 저장 경로, 저장 파일 명, 파일을 필수값으로 받아서 서버에 저장하는 API

API that receives file storage path, save file name, and file as required values and saves them to the server

#region Upload
/// <summary>
/// 파일 업로드
/// </summary>
/// <param name="path">파일 저장 경로(서버)</param>
/// <param name="filename">파일 저장 이름(서버)</param>
/// <param name="file">파일(클라이언트)</param>
/// <returns></returns>
//[EnableCors("CORS")]
[HttpPost("upload")]
public string Upload(
[Required][FromForm(Name = "path")]string path,
[Required][FromForm(Name = "filename")]string filename,
[Required][FromForm(Name = "file")] Microsoft.AspNetCore.Http.IFormFile file)
{
    try
    {
        //인코딩
        System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
        System.Text.Encoding.GetEncoding("windows-1254");

        if (!Directory.Exists(path))  // 폴더 존재 확인 
            Directory.CreateDirectory(path);   // 폴더 생성 

        //파일 저장
        using (var fileStream = new FileStream(path+@"\"+filename, FileMode.Create, FileAccess.Write))
            file.OpenReadStream().CopyTo(fileStream);

        return "true";
    }
    catch (Exception exception)
    {
        return exception.Message;
    }
}
#endregion