Home > Backend Development > C#.Net Tutorial > Example code for uploading and downloading files in ASP.NET

Example code for uploading and downloading files in ASP.NET

怪我咯
Release: 2017-03-30 11:53:49
Original
1860 people have browsed it

using System.IO;
//Check that the uploaded file is not empty

 if(File1.PostedFile!=null)
   {     
    string nam = File1.PostedFile.FileName ;
    //取得文件名(抱括路径)里最后一个"."的索引
    int i= nam.LastIndexOf(".");
    //取得文件扩展名
    string newext =nam.Substring(i);
    //这里我自动根据日期和文件大小不同为文件命名,确保文件名不重复
    DateTime now = DateTime.Now; 
    string newname=now.DayOfYear.ToString()+File1.PostedFile.ContentLength.ToString(); 
    //保存文件到你所要的目录,这里是IIS根目录下的upload目录.你可以改变.
    //注意: 我这里用Server.MapPath()取当前文件的绝对目录.在asp.net里""必须用""代替
    File1.PostedFile.SaveAs(Server.MapPath("upload"+newname+newext));    this.HyperLink1.NavigateUrl  ="upload"+newname+newext;    //得到这个文件的相关属性:文件名,文件类型,文件大小
    //fname.Text=File1.PostedFile.FileName;
    //fenc.Text=File1.PostedFile.ContentType ;
    //fsize.Text=File1.PostedFile.ContentLength.ToString();
   }
Copy after login

You can use File in the HTML control in .net to upload Field's upload control, after you drag it to the form, you can right-click to use it as a server-side control. Just write a few lines of code you want to upload. Download directly and connect to the file you want to download. Downloaded Upload the file to the server, directly add a hyperlink and download. The following are the classes used to upload files:
Description: You can use it by directly copying and pasting in the cs file. using System;
using System.IO;

using System.Web.UI.HtmlControls;namespace youjian 
{ 
 /// <summary> 
 /// UpFile 的摘要说明。 
 /// </summary> 
 public class UpFile 
 { 
  public UpFile() 
 { 
}#region 是否允许该扩展名上传IsAllowedExtension 
///<summary> 
///是否允许该扩展名上传 
///</summary> 
///<paramname = "hifile">HtmlInputFile控件</param> 
///<returns>允许则返回true,否则返回false</returns> 
public bool IsAllowedExtension(HtmlInputFile hifile) 
{ 
 string strOldFilePath = ""; 
 string strExtension = ""; //允许上传的扩展名,可以改成从配置文件中读出 
 string[]arrExtension = {".gif",".jpg",".jpeg",".bmp",".png"}; if(hifile.PostedFile.FileName != string.Empty) 
 { 
 strOldFilePath = hifile.PostedFile.FileName; 
 //取得上传文件的扩展名 
 strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf(".")); 
 //判断该扩展名是否合法 
  for(int i = 0;i<arrExtension.Length;i++) 
  { 
   if(strExtension.Equals(arrExtension[i])) 
   { 
    return true; 
   } 
  } 
 } 
 return false; 
} 
#endregion #region 判断上传文件大小是否超过最大值IsAllowedLength 
/// <summary> 
/// 判断上传文件大小是否超过最大值 
/// </summary> 
/// <param name="hifile">HtmlInputFile控件</param> 
/// <returns>超过最大值返回false,否则返回true.</returns> 
public bool IsAllowedLength(HtmlInputFile hifile) 
{ 
 //允许上传文件大小的最大值,可以保存在xml文件中,单位为KB 
 int i = 20; 
 //如果上传文件的大小超过最大值,返回flase,否则返回true. 
 if(hifile.PostedFile.ContentLength > i * 1024) 
 { 
  return false; 
 } 
 return true; 
} 
#endregion
#region 获取一个不重复的文件名GetUniqueString 
/// <summary> 
/// 获取一个不重复的文件名 
/// </summary> 
/// <returns></returns> 
public string GetUniqueString() 
{ 
 //得到的文件名形如:20050922101010 
 return DateTime.Now.ToString("yyyyMMddhhmmss"); 
} 
#endregion #region 删除指定文件DeleteFile 
/// <summary> 
/// 删除指定文件 
/// </summary> 
/// <param name="strAbsolutePath">文件绝对路径</param> 
/// <param name="strFileName">文件名</param> 
public void DeleteFile(string strAbsolutePath, string strFileName) 
{ 
//判断路径最后有没有/符号,没有则自动加上 
 if(strAbsolutePath.LastIndexOf("//") == strAbsolutePath.Length) 
 { 
  //判断要删除的文件是否存在 
  if(File.Exists(strAbsolutePath + strFileName)) 
  { 
   //删除文件 
   File.Delete(strAbsolutePath + strFileName); 
  } 
 } 
 else 
 { 
  if(File.Exists(strAbsolutePath + "//" + strFileName)) 
  { 
   File.Delete(strAbsolutePath + "//" + strFileName); 
  } 
 } 
} 
#endregion
#region 上传文件并返回文件名 SaveFile 
/// <summary> 
/// 上传文件并返回文件名 
/// </summary> 
/// <param name="hifile">HtmlInputFile控件</param> 
/// <param name="strAbsolutePath">绝对路径.如:Server.MapPath(@"Image/upload")与Server.MapPath(@"Image/upload/")均可,用/符号亦可</param> 
/// <returns>返回的文件名即上传后的文件名</returns> 
public string SaveFile(HtmlInputFile hifile,string strAbsolutePath) 
{ 
 string strOldFilePath = "",strExtension = "",strNewFileName = ""; //如果上传文件的文件名不为空 
 if(hifile.PostedFile.FileName != string.Empty) 
 { 
  strOldFilePath = hifile.PostedFile.FileName; 
  //取得上传文件的扩展名 
  strExtension = strOldFilePath.Substring(strOldFilePath.LastIndexOf(".")); 
  //文件上传后的命名 
  strNewFileName = GetUniqueString() + strExtension; 
  //如果路径末尾为/符号,则直接上传文件 
  if(strAbsolutePath.LastIndexOf("//") == strAbsolutePath.Length) 
  { 
   hifile.PostedFile.SaveAs(strAbsolutePath + strNewFileName); 
  } 
  else 
  { 
   hifile.PostedFile.SaveAs(strAbsolutePath + "//" + strNewFileName); 
  } 
 } 
 return strNewFileName; 
} 
#endregion 
#region 重新上传文件,删除原有文件CoverFile 
/// <summary> 
/// 重新上传文件,删除原有文件 
/// </summary> 
/// <param name="ffFile">HtmlInputFile控件</param> 
/// <param name="strAbsolutePath">绝对路径.如:Server.MapPath(@"Image/upload")与Server.MapPath(@"Image/upload/")均可,用/符号亦可</param> 
/// <param name="strOldFileName">旧文件名</param> 
public void CoverFile(HtmlInputFile ffFile,string strAbsolutePath,string strOldFileName) 
{ 
 //获得新文件名 
 string strNewFileName = GetUniqueString(); if(ffFile.PostedFile.FileName != string.Empty) 
 { 
 //旧图片不为空时先删除旧图片 
  if(strOldFileName != string.Empty) 
  { 
   DeleteFile(strAbsolutePath,strOldFileName); 
  } 
  SaveFile(ffFile,strAbsolutePath); 
 } 
} 
#endregion
Copy after login

C#.net File operations: upload, download, delete file list

1. File upload
-------- --
The following points:
HTML part:

<form id="form1" runat="server" method="post" enctype="multipart/form-data"> 
<input id="FileUpLoad" type="file" runat="server"/><br /> 
后台CS部分 按钮事件 
//string strFileFullName = System.IO.Path.GetFileName(this.FileUpLoad.PostedFile.FileName); 
//this.FileUpLoad.PostedFile.SaveAs(Server.MapPath("./xmlzip/") + strFileFullName);
Copy after login

2. File download
----------

ListBox的SelectedIndexChanged事件 设定相关下载连接 
protected void lst_DownLoadFileList_SelectedIndexChanged(object sender, EventArgs e) 
{ 
 try 
 { 
  string strJS = "window.open(&#39;xmlzip/"; 
  strJS += this.lst_DownLoadFileList.SelectedItem.Text.Trim(); 
  strJS += "&#39;); return false; "; 
  this.imgbtn_DownLoadFile.Attributes.Add("onclick", strJS); 
 } 
 catch (Exception ex) 
 { 
  ex.ToString(); 
 } 
}
Copy after login

Or you can also change the Text value of Label to achieve a super link for file download after clicking

this.Label1.Text = "<a href=/"xmlzip/a.rar/">a.rar</a>"
Copy after login

3. File deletion
---------

string strFilePath = Server.MapPath("../CountryFlowMgr/xmlzip/"+this.lst_DownLoadFileList.SelectedItem.Text.Trim()); 
if (File.Exists(strFilePath)) 
{ 
 File.Delete(strFilePath); 
 if (File.Exists(strFilePath)) 
 { 
  Response.Write("ok"); 
 } 
 else 
 { 
  Response.Write("ok"); 
 } 
}
Copy after login

4. Get the file list under the folder
-----------
#region Get the currently available file list
///


/// Get the currently available file list
///

/// Whether a prompt message needs to pop up

private void fn_getCurrFileList(bool IsAlert) 
{ 
 try 
 { 
  //查找xmlzip文件夹下 属于其本身UnitCoding的相关zip文件 
  string strXmlZipDirectory = Server.MapPath("../xmlzip/"); 
  if (Directory.Exists(strXmlZipDirectory)) 
  { 
   //DirectoryInfo di = new DirectoryInfo(Environment.CurrentDirectory); 
   DirectoryInfo di = new DirectoryInfo(strXmlZipDirectory);   FileInfo[] FI = di.GetFiles("*.zip");//只查.zip文件 
   if (FI.Length > 0) 
   { 
    lst_DownLoadFileList.Items.Clear(); 
    foreach (FileInfo tmpFI in FI) 
    { 
     ListItem tmpItem = new ListItem(); 
     tmpItem.Text = tmpFI.Name; 
     lst_DownLoadFileList.Items.Add(tmpItem); 
    } 
    lst_DownLoadFileList.SelectedIndex = 0; 
   } 
   else 
   { 
    if (IsAlert) 
    { 
     Response.write("查无可以下载的文件!"); 
    } 
   } 
  }  
 } 
 catch (Exception ex) 
 { 
  ex.ToString(); 
 } 
} 
#endregion
Copy after login

The above is the detailed content of Example code for uploading and downloading files in ASP.NET. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template