Home > Mobile >  Published Asp.Net Core App not able to save to wwwroot
Published Asp.Net Core App not able to save to wwwroot

Time:04-08

I have the below code working well on LocalHost. But once I publish to Azure it doesn't seem to save to wwwroot. Effectively what I want the user to be able to do is overwrite a template file saved within wwwroot. But I can't even get a file to save there - is there a permission that I should change or something. I believe I have the correct app.UseStaticFiles within Startup.cs etc.

Controller

public class HomeController : Controller
{
    private IHostingEnvironment Environment;
 
    public HomeController(IHostingEnvironment _environment)
    {
        Environment = _environment;
    }
 
    public IActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public IActionResult Index(List<IFormFile> postedFiles)
    {
        string wwwPath = this.Environment.WebRootPath;
        string contentPath = this.Environment.ContentRootPath;
 
        string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
 
        List<string> uploadedFiles = new List<string>();
        foreach (IFormFile postedFile in postedFiles)
        {
            string fileName = Path.GetFileName(postedFile.FileName);
            using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
            {
                postedFile.CopyTo(stream);
                uploadedFiles.Add(fileName);
                ViewBag.Message  = string.Format("<b>{0}</b> uploaded.<br />", fileName);
            }
        }
 
        return View();
    }
}

View

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <form method="post" enctype="multipart/form-data" asp-controller="Home" asp-action="Index">
        <span>Select File:</span>
        <input type="file" name="postedFiles" multiple />
        <input type="submit" value="Upload" />
        <br/>
        <span style="color:green">@Html.Raw(ViewBag.Message)</span>
    </form>
</body>
</html>

Code is based on below: enter image description here

CodePudding user response:

You code is correct, after my test, your files will save to wwwroot/wwwroot/Uploads folder. This is expected behavior.

enter image description here

And From your code, we can see

string path = Path.Combine(this.Environment.WebRootPath, "Uploads");

You can log in your kudu site to check it. All the files will in this folder.

And in your project side, seems below 3 files outside the Uploads folder, that why it can't be replaced.

enter image description here

  • Related