ASP.NET MVC 6에서 파일 업로드

Sep 10 2020

ASP.NET MVC 6에서 파일 / 이미지 업로드를 다듬는 데 문제가 있습니다. 대부분의 자습서는 구식 인 것처럼 보이며 새로운 자습서 중 일부도 의미가없는 내용을 참조하는 것 같습니다.

내 관점에서 :

<div class="form-group">
    @using (Html.BeginForm("Create", "PostNin", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <label asp-for="NinImageString" class="control-label"></label>
        <input type="file" name="files" class="form-control" />
    }

    @*<input asp-for="NinImageString" class="form-control" />
    <span asp-validation-for="NinImageString" class="text-danger"></span>*@
</div>
<div class="form-group">
    <label asp-for="NinImageCaption" class="control-label"></label>
    <input asp-for="NinImageCaption" class="form-control" />
    <span asp-validation-for="NinImageCaption" class="text-danger"></span>
</div>

그리고 내 컨트롤러에서 :

// GET: PostNins/Create
public IActionResult Create()
{
    return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,NinFk,NinDigit,NinImageString,NinImageCaption,NinNote")] PostNin postNin, IFormFile files)
{
    // need code here
        
    if (ModelState.IsValid)
    {
        _context.Add(postNin);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    return View(postNin);
}

내 이해는 이것을 풀기 위해 사용해야 IFormFile한다는 것입니다.

캡션이있는 이미지를 업로드 NinImages하고 나중에 액세스 할 수 있는 애플리케이션 폴더에 저장하고 싶습니다. 나도 그것에 대해 질문이 있다고 생각하지만 다른 질문에 대한 것입니다.

내 이해는 어떻게 든 이미지의 복사본을 wwwroot 아래의 디렉토리 시스템에 저장 한 다음 파일 경로를 데이터베이스에 문자열로 저장해야한다는 것입니다.

해결책:

내 새 컨트롤러는 아래와 같습니다. 참고로 fileTime은 중복을 방지하기 위해 각 업로드에 고유 한 값을 할당하기위한 것입니다. 이 경우에는 한 번에 하나의 파일 만 업로드 할 수 있기 때문에 작동합니다.

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Id,NinFk,NinDigit,NinImageString,NinImageCaption,NinNote")] PostNin postNin, IFormFile uploadFile)
    {


        if (uploadFile != null && uploadFile.Length > 0)
        {
            var fileTime = DateTime.UtcNow.ToString("yyMMddHHmmss");
            var fileName = fileTime + Path.GetFileName(uploadFile.FileName);
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/NinFileUploads", fileName);

            postNin.NinImageString = filePath;
            _context.PostNins.Add(postNin);
            _context.SaveChanges();

            using (var fileStream = new FileStream(filePath, FileMode.Create))
            {
                await uploadFile.CopyToAsync(fileStream);
            }
            //if (ModelState.IsValid)
            //{
            //    _context.Add(postNin);
            //    await _context.SaveChangesAsync();
            //    return RedirectToAction(nameof(Index));
            //}
            return RedirectToAction(nameof(Index));

        }
        return View(postNin);

답변

2 YiyiYou Sep 10 2020 at 11:33

다음은 데모 작업입니다.

PostNin 클래스 :

public class PostNin
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ImagePath { get; set; }
    }

제어 장치:

public async Task<bool> Create(PostNin postNin,IFormFile upload)
        {     
                if (upload != null && upload.Length > 0)
                {                
                    var fileName = Path.GetFileName(upload.FileName);
                    var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/images", fileName);
                    postNin.ImagePath = filePath;
                    _context.PostNins.Add(postNin);
                    _context.SaveChanges();
                    using (var fileSrteam = new FileStream(filePath, FileMode.Create))
                    {
                        await upload.CopyToAsync(fileSrteam);
                    }
                    return true;
                }
                return false;
        }

결과:

1 fligant Sep 10 2020 at 03:03

파일 업로드 컨트롤의 이름을 파일로 변경

<input type="file" name="files" class="form-control" />

먼저 IFormFile 파일 앞에 [FromForm]을 추가하고 작동하는지 시도하십시오.

Create([Bind("Id,NinFk,NinDigit,NinImageString,NinImageCaption,NinNote")] PostNin postNin, [FromForm]IFormFile files)

작동하지 않는 경우 새 IFormFile 파일 속성을 PostNin 클래스에 추가하거나이 작업의 모델로 새 클래스를 만들고 작업 매개 변수 앞에 [FromForm]을 추가합니다.

public class PostNinModel {
....
public IFormFile files { get; set; }
...
}

Create([FromForm] PostNinModel postNin)
1 SaeedGholamzadeh Sep 10 2020 at 03:04

이 솔루션 이름 속성에서 메소드 매개 변수 작성과 동일한 입력 요소에 대한 이름 속성을 설정하고 uploadFile로 설정된 메소드 매개 변수 작성

HTML

<input type="file" name="uploadFile" class="form-control" />

CS

Create([Bind("Id,NinFk,NinDigit,NinImageString,NinImageCaption,NinNote")] PostNin postNin, IFormFile uploadFile)