2014-12-07 77 views
0

我想使用c#函数将文件上传到服务器。我在WebMatrix中为ASP.NET(.CSHTML)WebPages使用了这个函数。在C#函数中使用HttpContext

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); 
       } 
      } 
     } 
    } 

我的问题是如何在上传表单文件中调用这个函数?

+0

Chec this:http://stackoverflow.com/questions/25125127/asp-net-mvc-4-c-sharp-httppostedfilebase-how-do-i-store-file – 2014-12-07 08:22:29

+0

不适合我,因为我不要使用MVC – Apurva 2014-12-07 10:00:52

回答

0

你是不是指如何从UI(aspx页面)调用这个函数?

如果是这样的话,只需添加一个文件上传控件,并在控件的click事件中调用此方法即可。

+0

不,我的意思是如何从(.CSHTML)页面调用这个函数。 aspx和cshtml页面代码都不同。 :) – Apurva 2014-12-07 07:27:51

+0

对不起!没有注意到你在这里使用(.cshtml)。没有经验,但我想即使是使用文件上传控件来上传文件。 – Vinay 2014-12-07 07:39:32

1

在代码中的微小变化,我曾在函数调用的参数HttpContext context,而不是增加新的变量,var currentContext = HttpContext.Current 代码是这样的:

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

感谢分享!