Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -166,4 +166,33 @@ public async Task AsyncLogoUpload_DisallowedFileType_ReturnsFailureJson()
Assert.AreEqual("File no allowed", GetValue<string>(result, "message"));
_mediaFileStoreMock.Verify(m => m.GetFileInfo(It.IsAny<string>()), Times.Never);
}

[TestMethod]
public async Task AsyncLogoUpload_NameTaken_KeepsTheExistingFile_AndSavesUnderAFreeName()
{
_permissionServiceMock.Setup(p => p.Authorize(StandardPermission.ManageSettings)).ReturnsAsync(true);
var folder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "grand-logo-" + Guid.NewGuid())).FullName;
try
{
await File.WriteAllTextAsync(Path.Join(folder, "logo.png"), "another store's logo");
var root = new Mock<IFileStoreEntry>();
root.Setup(r => r.PhysicalPath).Returns(folder);
_mediaFileStoreMock.Setup(m => m.GetDirectoryInfo("")).Returns(root.Object);
var file = CreateFormFile("logo.png", "image/png");
file.Setup(f => f.CopyToAsync(It.IsAny<Stream>(), It.IsAny<CancellationToken>()))
.Returns((Stream target, CancellationToken _) => target.WriteAsync("new"u8.ToArray()).AsTask());

var result = await CreateController().AsyncLogoUpload(file.Object);

Assert.IsTrue(GetValue<bool>(result, "success"));
Assert.AreEqual("logo-1.png", GetValue<string>(result, "imageUrl"));
Assert.AreEqual("another store's logo", await File.ReadAllTextAsync(Path.Join(folder, "logo.png")));
Assert.AreEqual("new", await File.ReadAllTextAsync(Path.Join(folder, "logo-1.png")));
}
finally
{
Directory.Delete(folder, true);
}
}
}

76 changes: 30 additions & 46 deletions src/Web/Grand.Web.AdminShared/Controllers/BasePictureController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,58 +89,42 @@ public virtual async Task<IActionResult> AsyncLogoUpload(IFormFile file)
message = "Unknown content type"
});
fileName = fileName.Replace(" ", "");
var fileInfo = await mediaFileStore.GetFileInfo(fileName);
if (fileInfo == null)
try
{
var filepath = mediaFileStore.GetDirectoryInfo("");
if (filepath != null)
{
await using (var stream = new FileStream(mediaFileStore.Combine(filepath.PhysicalPath, fileName),
FileMode.OpenOrCreate))
{
await file.CopyToAsync(stream);
}
var filepath = mediaFileStore.GetDirectoryInfo("");
if (filepath == null)
return Json(new {
success = false,
message = "Physical path not exist"
});

return Json(new {
success = true,
imageUrl = fileName
});
}
//the folder is shared by every store, so an existing file (another store's logo) is never replaced
var (stream, savedName) = CreateUnderFreeName(filepath.PhysicalPath, fileName);
await using (stream)
{
await file.CopyToAsync(stream);
}

return Json(new {
success = false,
message = "Physical path not exist"
});
}
catch (Exception ex)
{
return Json(new {
success = false,
message = ex.Message
});
}
return Json(new {
success = true,
imageUrl = savedName
});
}

//CreateNew refuses a taken name, also one taken by an upload running at the same time, so the next is tried
private (FileStream stream, string fileName) CreateUnderFreeName(string folder, string fileName)
{
var name = Path.GetFileNameWithoutExtension(fileName);
var extension = Path.GetExtension(fileName);
for (var i = 0; ; i++)
{
var filepath = mediaFileStore.GetDirectoryInfo("");
if (filepath != null)
var candidate = i == 0 ? fileName : $"{name}-{i}{extension}";
var path = mediaFileStore.Combine(folder, candidate);
try
{
return (new FileStream(path, FileMode.CreateNew), candidate);
}
catch (IOException) when (System.IO.File.Exists(path))
{
await using (var stream = new FileStream(mediaFileStore.Combine(filepath.PhysicalPath, fileName),
FileMode.OpenOrCreate))
{
await file.CopyToAsync(stream);
}

return Json(new {
success = true,
imageUrl = fileName
});
}

return Json(new {
success = false,
message = "Physical path not exist"
});
}
}
}
Loading