1

I have seen so many working examples of File uploading with MVC.

However, I want to follow a different approach such that, I want a little abstraction as follows:

I want to introduce a FileService, and inject that to the controller as a dependency. Let the service upload the file and return me a UploadedFile object.

A problem I am having right now is to upload to correct place/directory in file system or application root.

In a controller, I have access to Server object which I can call Server.MapPath and it does the magic, below I cant access to that Object since it is not a Controller.

How can I upload to anywhere in file system or in project root below?

public class FileService : IFileService
{
    private const string UploadBase = "/Files";

    public File UploadFile(HttpPostedFileBase file)
    {
        if (file != null)
        {
            string folder = DateTime.Today.Month + "-" + DateTime.Today.Year;

            string finalFolder = Path.Combine(UploadBase, folder);

            if (!Directory.Exists(finalFolder))
            {
               return Directory.CreateDirectory(finalFolder);
            }


            var filename = UploadFile(file, directoryInfo.Name + "/");


            var newFile = new File { ContentType = file.ContentType, FilePath = filename, Filename = file.FileName };

            return newFile;

        }

        return null;
    }

An error is : The SaveAs method is configured to require a rooted path, and the path '9-2013/037a9ddf-7ffe-4131-b223-c4b5435d0fed.JPG' is not rooted.

4
  • you mean you couldn't access the Server object ? Commented Sep 26, 2013 at 12:00
  • 1
    If you need to map the virtual path to the physical path outside of controller, you can use HostingEnvironment.MapPath method. Commented Sep 26, 2013 at 12:00
  • HttpContext.Current.Server? Commented Sep 26, 2013 at 12:00
  • @PatrykĆwiek wanna write that as answer. i ll accept that. Commented Sep 26, 2013 at 12:26

1 Answer 1

1

Re-stating what was noted in comments:

If you want to map the virtual path to the physical path outside of the controller, you can always use HostingEnvironment.MapPath method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.