public void AddDirAndFile() { var dir = new BackedUpDirectory() { Modified = DateTime.Now, Name = @"c:\root1" }; _dbService.AddDirectory(dir); var file1 = new BackedUpFile() { Name = "file1", ParentId = dir.Id, Modified = DateTime.Now }; _dbService.AddFile(file1); var dir2 = _dbService.GetDirectory(@"c:\root1"); Assert.True(dir.Equals(dir2)); var file2 = _dbService.GetFile("file1", dir.Id); Assert.True(file1.Id == file2.Id); }
// [ValidateAntiForgeryToken] public async Task <IActionResult> Upload() { if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType)) { return(BadRequest($"Expected a multipart request, but got {Request.ContentType}")); } // Used to accumulate all the form url encoded key value pairs in the // request. var formAccumulator = new KeyValueAccumulator(); string tempFilePath = null; var boundary = MultipartRequestHelper.GetBoundary( MediaTypeHeaderValue.Parse(Request.ContentType), _apiOptions.MultipartBoundaryLengthLimit); var reader = new MultipartReader(boundary, HttpContext.Request.Body); var section = await reader.ReadNextSectionAsync(); while (section != null) { var hasContentDispositionHeader = ContentDispositionHeaderValue .TryParse(section.ContentDisposition, out ContentDispositionHeaderValue contentDisposition); if (hasContentDispositionHeader) { if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition)) { tempFilePath = Path.GetTempFileName(); using (var targetStream = System.IO.File.Create(tempFilePath)) { await section.Body.CopyToAsync(targetStream); } } else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition)) { var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name); var encoding = GetEncoding(section); using (var streamReader = new StreamReader( section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { // The value length limit is enforced by MultipartBodyLengthLimit var value = await streamReader.ReadToEndAsync(); if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase)) { value = String.Empty; } formAccumulator.Append(key, value); if (formAccumulator.ValueCount > _apiOptions.ValueCountLimit) { throw new InvalidDataException($"Form key count limit {_apiOptions.ValueCountLimit} exceeded."); } } } } // Drains any remaining section body that has not been consumed and // reads the headers for the next section. section = await reader.ReadNextSectionAsync(); } // Bind form data to a model var formData = formAccumulator.GetResults(); BackedUpFile backedUpFile = null; if (formData.TryGetValue("backedUpFile", out var values)) { var jsonString = values[0]; backedUpFile = JsonConvert.DeserializeObject <BackedUpFile>(jsonString); if (backedUpFile.ParentId == 0) { if (formData.TryGetValue("path", out var path)) { path = Path.GetDirectoryName(path) .Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); var dir = _dbService.GetDirectory(path); backedUpFile.ParentId = dir.Id; } } } if (backedUpFile.ParentId == 0) { throw new Exception($"{backedUpFile.Name} has no parent"); } var formValueProvider = new FormValueProvider( BindingSource.Form, new FormCollection(formAccumulator.GetResults()), CultureInfo.CurrentCulture); var bindingSuccessful = await TryUpdateModelAsync(backedUpFile, prefix : "", valueProvider : formValueProvider); if (!bindingSuccessful) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } } else { try { FileHistory hist = null; if (backedUpFile.Id > 0) { hist = _dbService.UpdateFile(backedUpFile); } else { hist = _dbService.AddFile(backedUpFile); } if (!Directory.Exists(_storageOptions.BackupRoot)) { Directory.CreateDirectory(_storageOptions.BackupRoot); } var destPath = Path.Combine(_storageOptions.BackupRoot, $"{hist.Id}_{backedUpFile.Name}"); if (System.IO.File.Exists(destPath)) { throw new IOException($"file '{destPath}' exists when it shouldn't"); } System.IO.File.Move(tempFilePath, destPath); } catch (Exception ex) { return(BadRequest(ex)); } } // filePath is where the file is return(Json(backedUpFile)); }