public async Task <IActionResult> Index(UserDocumentRequest userDocument) { if (userDocument.Document == null) { ViewBag.Error = ErrorMessages.DOCUMENT_REQUIRED; return(View("Index")); } using (var memoryStream = new MemoryStream()) { //Get the file steam from the multiform data uploaded from the browser await userDocument.Document.CopyToAsync(memoryStream); //Build an multipart/form-data request to upload the file to Web API using var form = new MultipartFormDataContent(); using var fileContent = new ByteArrayContent(memoryStream.ToArray()); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(fileContent, "Document", userDocument.Document.FileName); var userName = new StringContent(userDocument.UserName); form.Add(userName, "UserName"); var client = new HttpClient(); var response = await client.PostAsync(apiBaseUrl, form); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsStringAsync(); return(RedirectToAction("Index")); } }
/// <summary> /// Created By : Deep Vyas | 11-Mar-2021 /// Description : To add user documents /// </summary> public async Task <int> Add(UserDocumentRequest userDocumentReq) { int result = 0; var user = await _dbContext.Users.SingleOrDefaultAsync(u => u.Name == userDocumentReq.UserName); if (user == null) { user = new User() { Name = userDocumentReq.UserName }; await _dbContext.Users.AddAsync(user); await _dbContext.SaveChangesAsync(); } if (user.UserId > 0) { Document document = new Document() { FileName = userDocumentReq.DocumentName, Path = userDocumentReq.DocumentPath, UserId = user.UserId }; await _dbContext.Documents.AddAsync(document); result = await _dbContext.SaveChangesAsync(); } return(result); }
public async Task <IActionResult> AddUserDocument([FromForm] UserDocumentRequest userDocumentRequest) { try { string extension = Path.GetExtension(userDocumentRequest.Document.FileName); if (extension != Constants.ALLOWED_EXTENSION) { return(BadRequest(new { ErrorMessage = ErrorMessages.ONLY_PDF_EXTENSION_ALLOWED })); } userDocumentRequest.DocumentName = $"{Guid.NewGuid()}{extension}"; string directory = Path.Combine(_hostingEnvironment.WebRootPath, Constants.DOCUMENT_PATH); string path = Path.Combine(directory, userDocumentRequest.DocumentName); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } using (Stream stream = new FileStream(path, FileMode.Create)) { userDocumentRequest.Document.CopyTo(stream); } userDocumentRequest.DocumentPath = Path.Combine(Constants.DOCUMENT_PATH, userDocumentRequest.DocumentName); int result = await _userDocumentRepository.Add(userDocumentRequest); if (result == 0) { return(NotFound()); } return(StatusCode(StatusCodes.Status201Created)); } catch (Exception ex) { return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message)); } }