1

I'm trying to upload file to server using a c# function. I am using this function for ASP.NET (.CSHTML) WebPages in WebMatrix.

public static void Upload(string fileSavePath, HttpContext context)
    {
        var fileCount = context.Request.Files.Count;
        if (fileCount > 0)
        {
            for (int i = 0; i < fileCount; i++)
            {
                var file = context.Request.Files[i];
                if (file.ContentLength > 0)
                {
                    var fileUpload = new WebImage(file.InputStream);
                    var newFileTitle = RandomString.GenRandomString(10, 4);
                    var fileExtention = Path.GetExtension(file.FileName).Trim();
                    var newFileName = newFileTitle + fileExtention;
                    var fileSaveLocation = HttpContext.Current.Server.MapPath(fileSavePath);
                    if(!Directory.Exists(fileSaveLocation))
                    {
                        Directory.CreateDirectory(fileSaveLocation);
                    }
                    fileUpload.Save(fileSaveLocation+"/"+newFileName);
                }
            }
        }
    }

My question is how to call this function in upload form file?

Apurva
  • 148
  • 1
  • 14

2 Answers2

1

A minor change in code worked for me instead of calling argument HttpContext context in the function added new variable as var currentContext = HttpContext.Current code was like:

public static void Upload(string fileSavePath) // Removed (HttpContext context)
{
    var currentContext = HttpContext.Current;
    /* Continue code from here */
}

Thanks for contributing!

Apurva
  • 148
  • 1
  • 14
0

Did you mean how to call this function from UI (aspx page) ?

If that is the case then, just add a file upload control and call this method on the click event of the control.

Vinay
  • 61
  • 6
  • No. I mean how to call this function from (.CSHTML) page. Both aspx and cshtml page codes are different. :) – Apurva Dec 07 '14 at 07:27
  • Ah sorry! Didn't notice you are using (.cshtml) here. Have no experience on that but I guess even that should be using the file upload control to upload the file. – Vinay Dec 07 '14 at 07:39