首页 > 代码库 > ASP.NET上传文件的几种方法
ASP.NET上传文件的几种方法
if (fileDealer.HasFile)//判断文件是否存在
{
string filepath = "";
try
{
string path = fileDealer.FileName;
string filename = path.Split(‘.‘)[0] + "_" + DateTime.Now.ToString("yyyyMMddHHmmss");//重名名
if (fileDealer.PostedFile.ContentLength > 50 * 1024 * 1024)
{
Page.ClientScript.RegisterStartupScript(GetType(), "", "<script>alert(‘上传文件不能超过50M!‘);</script>");
return;
}
string serverpath = @"~/Files/Activty/";//存放路径
string fileExtente = Path.GetExtension(fileDealer.FileName);//扩展名
if (!Directory.Exists(Server.MapPath(serverpath)))
{
Directory.CreateDirectory(Server.MapPath(serverpath));
}
filepath = Path.Combine(serverpath, filename + fileExtente);
fileDealer.SaveAs(Server.MapPath(filepath));
obj.Attachment = filepath;
}
catch (Exception ex)
{
throw ex;
}
}
/// upfile 的摘要说明。
///
public class upfile
{
private string path = null;
private string fileType = null;
private int sizes = 0;
///
/// 初始化变量
///
public upfile()
{
path = @"\uploadimages\"; //上传路径
fileType = "jpg|gif|bmp";
sizes = 200; //传文件的大小,默认200KB
}
/// 设置上传路径,如:uploadimages\
///
public string Path
{
set
{
path = @"\" + value + @"\";
}
}
/// 设置上传文件大小,单位为KB
///
public int Sizes
{
set
{
sizes = value * 1024;
}
}
/// 设置上传文件的类型,如:jpg|gif|bmp ///
public string FileType
{
set
{
fileType = value;
}
}
/// 上传图片
///
/// 上传控件名称
/// true则以当前时间创建文件夹,false则为设置的文件夹
/// 返回上传图片的相对路径
public string fileSaveAs(System.Web.UI.HtmlControls.HtmlInputFile name,bool creatDirectory)
{
try
{
string filePath=null;
//以当前时间修改图片的名字或创建文件夹的名字
string modifyFileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
//获得站点的物理路径
string uploadFilePath = null;
//如果为true则以当前时间创建文件夹,否则为设置的文件夹
if(creatDirectory)
{
uploadFilePath = System.Web.HttpContext.Current.Server.MapPath(".") + @"\" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + @"\";
}
else
{
uploadFilePath = System.Web.HttpContext.Current.Server.MapPath(".") + path;
}
//获得文件的上传的路径
string sourcePath=name.Value.Trim();
//判断上传文件是否为空
if(sourcePath == "" || sourcePath == null)
{
message("您没有上传数据呀,是不是搞错了呀!");
return null;
}
//获得文件扩展名
string tFileType = sourcePath.Substring(sourcePath.LastIndexOf(".")+1);
//获得上传文件的大小
long strLen = name.PostedFile.ContentLength;
//分解允许上传文件的格式
string[] temp = fileType.Split(‘|‘);
//设置上传的文件是否是允许的格式
bool flag = false;
//判断上传文件大小
if(strLen >= sizes)
{
message("上传的图片不能大于" + sizes + "KB");
return null;
}
//判断上传的文件是否是允许的格式
foreach(string data in temp)
{
if(data =http://www.mamicode.com/= tFileType)
{
flag = true ;
break;
}
}
//如果为真允许上传,为假则不允许上传
if(!flag)
{
message("目前本系统支持的格式为:"+fileType);
return null;
}
System.IO.DirectoryInfo dir=new System.IO.DirectoryInfo(uploadFilePath);
//判断文件夹否存在,不存在则创建
if(!dir.Exists)
{
dir.Create();
}
filePath = uploadFilePath + modifyFileName + "." + tFileType;
name.PostedFile.SaveAs(filePath);
filePath = path + modifyFileName + "." + tFileType;
catch
{
//异常
message("出现未知错误!");
return null;
}
}
{
System.Web.HttpContext.Current.Response.Write(" alert(‘"+msg+"‘);window.location=‘"+url+"‘ ");
}
{
System.Web.HttpContext.Current.Response.Write(" alert(‘"+msg+"‘); ");
}
}
}
1. C#实现Web文件的上传
如果没有这个属性,就不能实现上传。
DateTime now = DateTime.Now ;
//取现在时间到DataTime类的对象now中
string strBaseLocation = "D:\\web\\FC\\pic\\";
//这是文件将上传到的服务器的绝对目录
if (uploadfile1.PostedFile.ContentLength != 0) //判断选取对话框选取的文件长度是否为0
{
uploadfile1.PostedFile.SaveAs(strBaseLocation+now.DayOfYear.ToString()+uploadfile1.PostedFile.ContentLength.ToString()+".jpg");
//执行上传,并自动根据日期和文件大小不同为文件命名,确保不重复
Label1.Text="图片1已经上传,文件名为:"+now.DayOfYear.ToString()+uploadfile1.PostedFile.ContentLength.ToString()+".jpg";
navigator.Insert(System.Xml.TreePosition.After, XmlNodeType.Element,"pic1","","") ;
navigator.Insert(System.Xml.TreePosition.FirstChild, XmlNodeType.Text,"pic1","","") ;
navigator.Value= http://www.mamicode.com/now.DayOfYear.ToString()+uploadfile1.PostedFile.ContentLength.ToString()+".jpg" ;
navigator.MoveToParent() ;
}
上面的代码用于笔者开发的一个使用XML文件存储新闻信息的系统中,后面几句代码作用是写上传文件信息到XML文件中。如果要上传其他类型文件,只需要将jpg改为相应类型的后缀名即可,如改为doc即可上传Word文件,浏览器即可直接浏览上传的Word文件。
--------------------------------------------------------------------------------
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
using System.Configuration;
using System.Drawing;
{
/// <summary>
/// 这是一个用于玩家投稿中实现玩家上传文件功能中用到的相应的函数的功能模块
/// </summary>
public class FileUpload
{
public enum File //定义一个人用于存放玩家上传文件信息的一个数组
{
FILE_SIZE , //大小
FILE_POSTNAME, //类型(文件后缀名)
FILE_SYSNAME , //系统名
FILE_ORGINNAME, //原来的名字
FILE_PATH //文件路径
}
private static Random rnd = new Random(); //获取一个随机数
{
string[] arr = new String[5];
string FileName = GetUniquelyString(); //获取一个不重复的文件名
string FileOrginName = file.PostedFile.FileName.Substring
if(file.PostedFile.ContentLength<=0)
{ return null; }
string postFileName;
string FilePath = Upload_Dir.ToString();
string path = FilePath + "\\";
try
{
int pos = file.PostedFile.FileName.LastIndexOf(".")+1;
postFileName = file.PostedFile.FileName.Substring(pos,file.PostedFile.FileName.Length-pos);
file.PostedFile.SaveAs(path+FileName+"."+postFileName); //存储指定的文件到指定的目录
}
catch(Exception exec)
{
throw(exec);
}
double size = Math.Round(file.PostedFile.ContentLength/unit,2);
arr[(int)File.FILE_SIZE] = size.ToString(); //文件大小
arr[(int)File.FILE_POSTNAME] = postFileName; //文件类型(文件后缀名)
arr[(int)File.FILE_SYSNAME] = FileName; //文件系统名
arr[(int)File.FILE_ORGINNAME] = FileOrginName; //文件原来的名字
arr[(int)File.FILE_PATH]=path+FileName+"."+postFileName; //文件路径
return arr;
}
{
if (sqlstr==String.Empty)
return false;
SqlCommand myCommand = new SqlCommand(sqlstr, myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
return true;
}
{
const int RANDOM_MAX_VALUE = http://www.mamicode.com/1000;
string strTemp,strYear,strMonth,strDay,strHour,strMinute,strSecond,strMillisecond;
int rndNumber = rnd.Next(RANDOM_MAX_VALUE);
strYear = dt.Year.ToString ();
strMonth = (dt.Month > 9)? dt.Month.ToString() : "0" + dt.Month.ToString();
strDay = (dt.Day > 9)? dt.Day.ToString() : "0" + dt.Day.ToString();
strHour = (dt.Hour > 9)? dt.Hour.ToString() : "0" + dt.Hour.ToString();
strMinute = (dt.Minute > 9)? dt.Minute.ToString() : "0" + dt.Minute.ToString();
strSecond = (dt.Second > 9)? dt.Second.ToString() : "0" + dt.Second.ToString();
strMillisecond = dt.Millisecond.ToString();
}
}
}
HttpWorkerRequestwr=(HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));
byte[]bs=wr.GetPreloadedEntityBody();
.
if(!wr.IsEntireEntityBodyIsPreloaded())
{
intn=1024;
byte[]bs2=newbyte[n];
while(wr.ReadEntityBody(bs2,n)>0)
{
..
}
}
{
public FileUpLoad()
{}
/**////
/// 上传文件名称
///
public string FileName
{
get
{
return fileName;
}
set
{
fileName = value;
}
}
private string fileName;
/// 上传文件路径
///
public string FilePath
{
get
{
return filepath;
}
set
{
filepath = value;
}
}
private string filepath;
/// 文件扩展名
///
public string FileExtension
{
get
{
return fileExtension;
}
set
{
fileExtension = value;
}
}
private string fileExtension;
}
<Application>
<FileUpLoad>
<Format>.jpg|.gif|.png|.bmp
</FileUpLoad>
</Application>
{
FileUpLoad fp = new FileUpLoad();
string fileName,fileExtension;
string saveName;
//建立上传对象
//
HttpPostedFile postedFile = InputFile.PostedFile;
fileExtension = System.IO.Path.GetExtension(fileName);
//根据类型确定文件格式
//
AppConfig app = new AppConfig();
string format = app.GetPath("FileUpLoad/Format");
//如果格式都不符合则返回
//
if(format.IndexOf(fileExtension)==-1)
{
throw new ApplicationException("上传数据格式不合法");
}
//根据日期和随机数生成随机的文件名
//
if(myfileName != string.Empty)
{
fileName = myfileName;
}
{
Random objRand = new Random();
System.DateTime date = DateTime.Now;
//生成随机文件名
saveName = date.Year.ToString() + date.Month.ToString() + date.Day.ToString() + date.Hour.ToString() + date.Minute.ToString() + date.Second.ToString() + Convert.ToString(objRand.Next(99)*97 + 100);
fileName = saveName + fileExtension;
}
DirectoryInfo upDir = new DirectoryInfo(phyPath);
if(!upDir.Exists)
{
upDir.Create();
}
//保存文件
//
try
{
postedFile.SaveAs(phyPath + fileName);
fp.FileExtension = fileExtension;
fp.FileName = fileName;
}
catch
{
throw new ApplicationException("上传失败!");
}
return fp;
}
{
//获取由客户端指定的上传文件的访问
HttpPostedFile upFile=f_IFile.PostedFile;
//得到上传文件的长度
int upFileLength=upFile.ContentLength;
//得到上传文件的客户端MIME类型
string contentType = upFile.ContentType;
byte[] FileArray=new Byte[upFileLength];
return FileArray;
}
using System.Data;
using System.Web;
using System.IO;
using Ruixin.WorkFlowDB;
using RXSuite.Base;
using RXSuite.Component;
using RuixinOA.BusinessFacade;
{
/**////
/// NetUFile 的摘要说明。
///
public class OpenFile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//从数据库中取出要下载的文件信息
RuixinOA.BusinessFacade.RX_OA_FileManager os = new RX_OA_FileManager();
EntityData data = http://www.mamicode.com/os.GetFileDetail(id);
{
DataRow dr = (DataRow)data.Tables["RX_OA_File"].Rows[0];
context.Response.Buffer = true;
context.Response.Clear();
context.Response.ContentType = dr["CContentType"].ToString();
context.Response.AddHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(dr["CTitle"].ToString()));
context.Response.BinaryWrite((Byte[])dr["CContent"]);
context.Response.Flush();
context.Response.End();
}
}
public bool IsReusable
{
get { return true;}
}
}
}
HttpWebResponse hwr = (HttpWebResponse)hwq.GetResponse();
byte[] bytes = new byte[hwr.ContentLength];
Stream stream = hwr.GetResponseStream();
stream.Read(bytes,0,Convert.ToInt32(hwr.ContentLength));
//HttpContext.Current.Response.BinaryWrite(bytes);