Alan Fisher
Alan Fisher

Reputation: 2055

How do I store an uploaded file to a location other than the application folder in MVC application

I can successfully upload a file using this code:

 [HttpPost]
    public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
    {
        // The Name of the Upload component is "attachments" 
        foreach (var file in attachments)
        {
            // Some browsers send file names with full path. This needs to be stripped.
            var fileName = Path.GetFileName(file.FileName);
            var physicalPath = Path.Combine(Server.MapPath("~/App_Data"), fileName);
            file.SaveAs(physicalPath);
        }
        // Return an empty string to signify success
        return Content("");
    }

But this puts the file in the running application App_Data folder. I want to put the file in a share on my LAN. I have tried the code below but it always appends myPath to the path of the application:

 [HttpPost]
public ActionResult Save(IEnumerable<HttpPostedFileBase> attachments)
    {
        // The Name of the Upload component is "attachments" 
        foreach (var file in attachments)
        {

// Some browsers send file names with full path. This needs to be stripped.
            var fileName = Path.GetFileName(file.FileName);
            //add possible new folder name to path
            var myPath = "//my-server-myshare/myfolder/";
            //combine with file name 
            var physicalPath = Path.Combine(Server.MapPath(myPath), fileName);

            file.SaveAs(physicalPath);
        }
        // Return an empty string to signify success
        return Content("");
    }

How can I force this to save in the URL I have as myPath?

Upvotes: 2

Views: 2303

Answers (1)

X3074861X
X3074861X

Reputation: 3819

Network shares need to be full UNC paths, so flip your slashes around :

var myPath = @"\\my-server-myshare\myfolder\";

You could also just create the file directly :

file.Create(@"\\my-server-myshare\myfolder\");

Upvotes: 3

Related Questions