Skip to content

Http posted file save as #458

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
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 @@ -313,6 +313,7 @@ internal HttpPostedFile() { }
public string ContentType { get { throw new System.PlatformNotSupportedException("Only supported when running on ASP.NET Core or System.Web");} }
public string FileName { get { throw new System.PlatformNotSupportedException("Only supported when running on ASP.NET Core or System.Web");} }
public System.IO.Stream InputStream { get { throw new System.PlatformNotSupportedException("Only supported when running on ASP.NET Core or System.Web");} }
public void SaveAs(string filename) { throw new System.PlatformNotSupportedException("Only supported when running on ASP.NET Core or System.Web");}
}
public abstract partial class HttpPostedFileBase
{
Expand Down
17 changes: 17 additions & 0 deletions src/Microsoft.AspNetCore.SystemWebAdapters/HttpPostedFile.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Globalization;
using System.IO;
using Microsoft.AspNetCore.Http;

Expand All @@ -19,4 +20,20 @@ public sealed class HttpPostedFile
public int ContentLength => (int)File.Length;

public Stream InputStream => File.OpenReadStream();

public void SaveAs(string filename)
{

if (!Path.IsPathRooted(filename))
{
throw new HttpException(string.Format(CultureInfo.InvariantCulture,
"The SaveAs method is configured to require a rooted path, and the path '{0}' is not rooted", filename));
}

using (var fileStream = new FileStream(filename, FileMode.Create))
{
InputStream.Seek(0, SeekOrigin.Begin);
InputStream.CopyTo(fileStream);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,16 @@ public void InputStream()
// Assert
Assert.Equal(expected.Object, stream);
}

[Fact]
public void SaveAs()
{
var file = new Mock<IFormFile>();
var expectedStream = new Mock<Stream>();
file.Setup(f => f.OpenReadStream()).Returns(expectedStream.Object);

var posted = new HttpPostedFile(file.Object);
Assert.Throws<HttpException>(() => posted.SaveAs("InvalidPath"));
}

}