Asp.net(c#)文件上传于下载
推荐于2016-02-20
我这里有个上传的函数,下载的还没做过(新手,目前还没用到),你看看吧能不能用了。
public void Upload(string path, System.Web.UI.WebControls.FileUpload fileupload)
{
bool fileOK = false;
if (FileUpload1.HasFile)
{
string fileException = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();
//获取指定路劲字符串的后缀名,并转化为小写
string[] allowExcption = { ".jpg", ".jpeg", ".bmp",".gif" };
//定义允许的后缀名
for (int i = 0; i < allowExcption.Length; i++)
{
if (fileException == allowExcption[i])
{
fileOK = true;
}
}
}
if (fileOK)
{
//判断文件是否存在,若不在则创建路径
if (System.IO.Directory.Exists(path))
{
//MessageBox.Show("该目录已经存在","信息提示");
}
else
{
System.IO.Directory.CreateDirectory(path);//创建文件路径
}
fileupload.SaveAs(path + "\\" + fileupload.FileName);//上传文件
}
else
{
Response.Write("<Script>alert('不支持此格式文件上传')</Script>");
return;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string serverpath = Server.MapPath("~/ImageFile");
string imapath = "~/ImageFile/" + FileUpload1.FileName;
Upload(serverpath, this.FileUpload1);
Image1.ImageUrl = imapath;
serverpath = Server.MapPath("~/ImageFile");
imapath = "~/ImageFile/" + FileUpload1.FileName;
Image1.ImageUrl = imapath;
Upload(serverpath, this.FileUpload1);
}
这部分是调用的(预览的功能),你要上传的话改成数据库操作就可以了,存放上传的路劲,文件的话她会自动生成文件夹放在里面的。
//以字符流的形式下载文件
var fs = new FileStream(“服务器端文件的路径”, FileMode.Open);
var bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("123.txt", System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
再详细点?加50分