简体   繁体   中英

Cannot upload file in mvc

I am uploading MVC website on web-server for the first time. Everything worked well except file upload option. Whenever I try to upload a file, it prompts me this error:

The SaveAs method is configured to require a rooted path, and the path '' is not rooted.

Error details is somehow showing a path of my project that I created on my local machine.

System.Web.HttpException (0x80004005): The SaveAs method is configured to require a rooted path, and the path '' is not rooted. at Printrpk.Controllers.ProductController.Create(ProductModels product) in C:\\Projects\\Carting\\Carting\\Carting\\Controllers\\ProductController.cs:line 145

I have tried multiple ways to check if my code is wrong, but I couldn't able to make it work.

This is what I have written under Create Action

foreach (string fileName in Request.Files)
{
    HttpPostedFileBase file = Request.Files[fileName];
    fName = file.FileName;
    if (file != null && file.ContentLength > 0)
    {
        var originalDirectory = new DirectoryInfo(string.Format("{0}images", Server.MapPath(@"/")));
        var pathString = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ProductImages");
        var filename = Path.GetFileName(file.FileName);

        bool isExists = System.IO.Directory.Exists(pathString);
        if (!isExists)
        {
            System.IO.Directory.CreateDirectory(pathString);
        }

        path = string.Format("{0}//{1}", pathString, filename);
        file.SaveAs(path);
    }
}

This controller works fine when I do not upload any image. I have checked my web.config which is already pointing towards web-server.

This is included in Create View

<input name="file" type="file" multiple />

Also I already have targeted folder in my base folder

Use Server.MapPath() to get the physical path that corresponds to a virtual path. Assuming you app contains a folder named Images which contains a subfolder named ProductImages , then

var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/ProductImages"), fileName);
file.SaveAs(path);

Side note: Consider adding a parameter IEnumerable<HttpPostedFileBase> file to you POST method so it is bound with the selected files (or better, include that as a property in your view model) rather than using Request.Files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM