2017-11-20 5 views
0

asp.net 코어 2 면도기 페이지에서 간단한 파일 업로드를 시도하고 있습니다. 아래 코드가 있습니다. 불완전하다는 것을 알고 계십시오. 내 VS2017에서 실행할 때, 내 FileUpload 개체를 확인하고, 그것은 불행히도 null입니다. 나는 그것이 null 외에 뭔가가 있기를 바랄 것이고 나는 그것으로부터 어떤 데이터를 얻기 위해 스트림을 생성 할 수있을 것이다. 그러나 개체가 null 인 경우 제대로 연결되어 있지 않은 것으로 의심됩니다. 어떤 생각이라도 감사합니다. 감사. CS 뒤에ASP.NET 코어 2 면도기 페이지의 파일 업로드

코드 :

public class PicturesModel : PageModel 
{ 
    public PicturesModel() 
    { 

    } 
    [Required] 
    [Display(Name = "Picture")] 
    [BindProperty] 
    public IFormFile FileUpload { get; set; } 

    public async Task OnGetAsync() 
    { 

    } 

    public async Task<IActionResult> OnPostAsync() 
    { 
     //FileUpload is null 
     return RedirectToPage("/Account/Pictures"); 
    } 
} 

프런트 엔드 cshtml 파일;

<form method="post" enctype="multipart/form-data"> 
    <label asp-for="FileUpload"></label> 
    <input type="file" asp-for="FileUpload" id="file" name="file" /> 
    <input type="submit" value="Upload" /> 
</form> 

답변

0

귀하의 속성은 FileUpload 이름이 있지만 TagHelper에 의해 생성 된 name 속성을 재정의 속성 이름과 일치하지 않는 file로 이름을 변경했다.

변경 (name="FileUpload"이다) 올바른 name 속성을 생성되도록

<input type="file" asp-for="FileUpload" /> 

에 뷰 코드. id="file"의 제거 또한 사용자가 <label>을 클릭하면 연결된 컨트롤에 포커스가 설정되지 않았 음을 의미합니다.

+0

스티븐 감사합니다. 이름 속성을 무시하면 문제가 발생한 것으로 보입니다. 나는 이것을 꺼 냈고 FileUpload 객체는 올바른 값으로 보이는 것으로 통과합니다. 매우 감사. 감사합니다. –

0

저는 오늘 아침 모든 종류의 솔루션을 시험하기 위해 많은 시간을 보냈습니다. 아무도 작동하지 않는 것 같았습니다. 그러나 결국, 나는 이것을 생각해 냈습니다. 즐기십시오.

/// <summary> 
    /// Upload a .pdf file for a particular [User] record 
    /// </summary> 
    [AllowAnonymous] 
    [HttpPost("uploadPDF/{UserId}")] 
    public async Task<IActionResult> uploadPDF(string UserId, IFormFile inputFile) 
    { 
     try 
     { 
      if (string.IsNullOrEmpty(UserId)) 
       throw new Exception("uploadPDF service was called with a blank ID."); 
      Guid id; 
      if (!Guid.TryParse(RequestId, out id)) 
       throw new Exception("uploadPDF service was called with a non-GUID ID."); 

      var UserRecord = dbContext.Users.FirstOrDefault(s => s.UserID == id); 
      if (UserRecord == null) 
       throw new Exception("User record not found."); 

      var UploadedFileSize = Request.ContentLength; 
      if (UploadedFileSize == 0) 
       throw new Exception("No binary data received."); 

      var values = Request.ReadFormAsync(); 
      IFormFileCollection files = values.Result.Files; 
      if (files.Count == 0) 
       throw new Exception("No files were read in."); 

      IFormFile file = files.First(); 
      using (Stream stream = file.OpenReadStream()) 
      { 
       BinaryReader reader = new BinaryReader(stream); 
       byte[] bytes = reader.ReadBytes((int)UploadedFileSize); 

       Trace.WriteLine("Saving PDF file data to database.."); 
       UserRecord.RawData = bytes; 
       UserRecord.UpdatedOn = DateTime.UtcNow; 
       dbContextWebMgt.SaveChanges(); 
      } 

      return new OkResult(); 
     } 
     catch (Exception ex) 
     { 
      logger.LogError(ex, "uploadPDF failed"); 
      return new BadRequestResult(); 
     } 
    }