Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

주의사항

가이드로 제공되는 아래 코드는 샘플 코드로서, 리소스 관리나 보안 관련 처리에 대해서는 미흡할 수 있습니다.

단순 참고용으로만 사용해주세요.


1. 이미지, 동영상, 파일 업로드

Code Block
languagec#
themeEmacs
titleC#
linenumberstrue
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

// absolute path to WEB ROOT directory
private const string WEB_ROOT_ABS_PATH = @"C:\workspace\SynapEditor_C#\SynapEditor\wwwroot";
 
// absolute path to directory where the files are to be uploaded
private readonly string UPLOAD_DIR_ABS_PATH = Path.Combine(WEB_ROOT_ABS_PATH, "uploads");

/*
 * file upload API
 */
[HttpPost("api/uploadFile")]
public IActionResult UploadFile(IFormFile file)
{
    string uploadFileAbsPath = SaveFileToDisk(file).Result;
    string uploadFileRelPath = Path.GetRelativePath(UPLOAD_DIR_ABS_PATH, uploadFileAbsPath);
    
    return Ok(new {uploadPath = uploadFileRelPath});
}

/*
 * save data received from client-side to local filesystem
 */ 
private async Task<string> SaveFileToDisk(IFormFile file)
{
    string extension = Path.GetExtension(file.FileName);
    string uploadFileName = $"{Guid.NewGuid()}{extension}";
    string uploadFileAbsPath = Path.Combine(UPLOAD_DIR_ABS_PATH, uploadFileName);

    using (var fileStream = new FileStream(uploadFileAbsPath, FileMode.Create))
    {
        await file.CopyToAsync(fileStream);
    }

    return uploadFileAbsPath;
}

...