用户用input选择了一个文件,点击按钮上传到服务器上,并返回相关信息的函数:
///
/// 将本地文件从 HtmlInputFile 控件上传到服务器上
///
public class UploadFileFormHtmlInputFile
{
///
/// 将本地文件从 HtmlInputFile 控件上传到服务器上
/// --------------说明------------------
/// 限制大小问题 system.web 下 httpRuntime executionTimeout="800" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false"
/// string[] xx = GO(HtmlInputFileID, "\\Resourse\\image\\userdata\\","jpg|gif",true);
/// 注意:如果上传失败,xx[0]为"error",xx[1]为错误原因!
/// xx[0]:新文件名
/// xx[1]:文件类型(文件后缀名)
/// xx[2]:文件大小
/// xx[3]:文件上传前的名字
/// xx[4]:文件物理路径
/// xx[5]:文件相对服务器的路径
/// --------------------------------------
///
/// htmlinputfile的id
/// 服务器上的文件夹名称如 "Resourse\\image\\userdata\\"
/// 允许上传的类型如"jpg|gif|png|txt",""为不限制
/// 是否改名,默认修改,即为true
/// 指定文件的新名字 不要带扩展名,如"abc"
///
public string[] GO(HtmlInputFile file, string ServerDir, string TypeString, bool ChangeFileName, string NewFileName)
{
Thread.Sleep(100);
string[] arr = new String[6];
try
{
if (file.PostedFile.ContentLength <= 0)
{
arr[0] = "error";
arr[1] = "没有文件!";
return arr;
}
int pos = file.PostedFile.FileName.LastIndexOf(".") + 1;
string postFileName = file.PostedFile.FileName.Substring(pos, file.PostedFile.FileName.Length - pos); ;
TypeString = TypeString.ToLower();
if (TypeString.Length != 0 & TypeString.IndexOf(postFileName) == -1)
{
arr[0] = "error";
arr[1] = "允许上传类型:" + TypeString + " 当前类型:" + postFileName;
return arr;
}
string FileOrginName = file.PostedFile.FileName.Substring(file.PostedFile.FileName.LastIndexOf("\\") + 1);
string FileName = FileOrginName.Substring(0, pos - 1);
if (ChangeFileName)
{
if (NewFileName.Length == 0)
{
Random r = new Random();
int newstr = r.Next(0, 500);
FileName = DateTime.Now.ToString("yyyyMMddhhmmssffff") + newstr.ToString();
}
else
{
FileName = NewFileName;
}
}
string FilePath = System.Web.HttpContext.Current.Server.MapPath("~") + ServerDir.ToString();
if (!System.IO.Directory.Exists(FilePath))
{
System.IO.Directory.CreateDirectory(FilePath);
}
file.PostedFile.SaveAs(FilePath + FileName + "." + postFileName); //存储指定的文件到指定的目录
double unit = 1024;
double size = Math.Round(file.PostedFile.ContentLength / unit, 2);
arr[0] = FileName + "." + postFileName; //新文件名
arr[1] = postFileName; //文件类型(文件后缀名)
arr[2] = size.ToString(); //文件大小
arr[3] = FileOrginName; //文件上传前的名字
arr[4] = FilePath + FileName + "." + postFileName; //文件路径
arr[5] = "\\" + ServerDir + FileName + "." + postFileName; //相对服务器的文件路径
return arr;
}
catch (Exception ErrMsg)
{
arr[0] = "error";
arr[1] = ErrMsg.ToString();
return arr;
}
}
}
使用方法:
修改上传大小限制可以去web.config文件中修改
system.web 下 httpRuntime executionTimeout="800" maxRequestLength="40960"
useFullyQualifiedRedirectUrl="false"
//下面是调用方法
string[] xx = GO(HtmlInputFileID, "\\Resourse\\image\\userdata\\","jpg|gif",true);
//返回值说明:
xx[0]:新文件名
xx[1]:文件类型(文件后缀名)
xx[2]:文件大小
xx[3]:文件上传前的名字
xx[4]:文件物理路径
xx[5]:文件相对服务器的路径