Major Productions
Major Productions

Reputation: 6062

Is it possible to save uploaded files in ~/Content? (ASP.NET MVC2)

I've been trying to save incoming uploaded images in ~/Content on my development machine while debugging/testing, but no files are being transferred there. Does the folder allow for images to be saved/transferred to it, or will I need to save them in ~/App_Data?


EDIT: Code I'm using:

public ActionResult(AdminGameEditModel formData)
{
    Game game = new Game();

    AutoMapper.Mapper.Map<AdminGameEditModel, Game>(formData, game);

    if (formData.BoxArt.ContentLength > 0 && formData.IndexImage.ContentLength > 0)
    {
        var BoxArtName = Path.GetFileName(formData.BoxArt.FileName);
        var BoxArtPath = Path.Combine(Server.MapPath("~/Content/Images/BoxArt"), BoxArtName);
        game.BoxArtPath = BoxArtPath;
        formData.BoxArt.SaveAs(BoxArtPath);

        var IndexImageName = Path.GetFileName(formData.IndexImage.FileName);
        var IndexImagePath = Path.Combine(Server.MapPath("~/Content/Images/GameIndexImages"), IndexImageName);
        game.IndexImagePath = IndexImagePath;
        formData.IndexImage.SaveAs(IndexImagePath);
    }

    // rest of controller method
}

Both files are HttpPostedFileBase objects. The server I'm using currently is just the ASP.NET server that runs during VS debugging.

Upvotes: 0

Views: 1753

Answers (2)

ventaur
ventaur

Reputation: 1851

You should be able to save uploaded files to any directory you choose. The catch is ensuring that the service account that ASP.NET runs under has write permissions to that folder. For IIS 7 or later, it is likely the Network Service account on the server. To be sure, look at the Application Pool your site is running under in IIS and check the identity it is running under.


Update:

I see. You can try this to see if there is an issue with the SaveAs method of that type (I remember some people having issues with it).

Instead of:

formData.BoxArt.SaveAs(BoxArtPath);

try:

using (var output = new FileStream(BoxArtPath, FileMode.CreateNew)) {
  var data = new byte[formData.BoxArt.ContentLength];
  formData.BoxArt.InputStream.Read(data, 0, data.Length);
  output.Write(data, 0, data.Length);
}

Upvotes: 1

LeftyX
LeftyX

Reputation: 35597

You can copy/save images and files wherever you want on your disk.
You only have to check if the IIS process has access to the folder.
I tend to create a custom folder where I put my uploaded files.

Upvotes: 2

Related Questions