实现按日期命名C#文件上传,做开发的应该能够用得了吧!
“附件说明”边的TextBox:Id=TextBox1
“浏览”:Id=UpLoadFile
“上传”:Id=AddFile
文件目录:wwwroot/myWeb/userfiles/upload
实现按日期命名C#文件上传代码如下:
- private void AddFile_Click(object sender, System.EventArgs e){
- if(UpLoadFile.PostedFile.FileName.Trim()!=""){
- String fileName =UpLoadFile.PostedFile.FileName.Substring
(UpLoadFile.PostedFile.FileName.LastIndexOf("\\")+1,
UpLoadFile.PostedFile.FileName.Length- 1 - UpLoadFile.
PostedFile.FileName.LastIndexOf("\\"));- ///取到当前时间的年、月、日、分、秒和毫秒的值,并使用字符串格式把它们组合成一个字符串
- String fileTime = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()+
DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString()+
DateTime.Now.Second.ToString() + DateTime.Now.Minute.ToString()+
DateTime.Now.Millisecond.ToString();- ///在时间字符串后面添加一个随机数和文件的后缀名
- String src=fileName.Substring(fileName.LastIndexOf(".")+1,
fileName.Length-fileName.LastIndexOf(".")-1)。ToLower();- if(src.ToLower()=="rar" || src.ToLower()=="doc" || src.ToLower()=="xls"){
- fileName =fileTime + GetRandomint() + "." + src;
- ///上载文件到服务器硬盘
- UpLoadFile.PostedFile.SaveAs(Server.MapPath(Request.ApplicationPath) +
"\\userfiles\\upload\\" + fileName);- if(TextBox1.Text.Trim()==""){
- FCKeditor1FCKeditor1.Value=FCKeditor1.Value+"
<a href=userfiles/upload/"+fileName+">下载附件</a><br>";- }
- else{
- FCKeditor1FCKeditor1.Value=FCKeditor1.Value+"
<a href=userfiles/upload/"+fileName+">"+TextBox1.Text.ToString()+"< /a><br>";- }
- }
- else{
- Response.Write("<script>alert(\"文件格式不正确,请上传格式为RAR的文件!\")</script>");
- }
- }
- }
- private String GetRandomint(){
- Random random = new Random();
- return(random.Next(10000)。ToString());
- //产生一个小于10000的随机正整数
- }
以上介绍实现按日期命名C#文件上传
【编辑推荐】