当前位置:编程学习 > C#/ASP.NET >>

asp.net页面上传附件(可以任意添加多个上传控件)和下载附件(下载附件要是从数据库里面读取的)

asp.net页面上传附件(可以任意添加多个上传控件)
下载附件(下载附件要是从数据库里面读取的)


请帮我一下...谢了...
(刚才一个问题马上就搞定了..希望这个问题也能有人帮我一下..在这里先谢了) --------------------编程问答-------------------- 帮顶学习,在给我点分把 --------------------编程问答-------------------- 呵呵...谢了..

--------------------编程问答-------------------- 这里要新增加一个表
上传:把文件传到服务器,同时要写入数据库一条记录
下载:从数据库读出 --------------------编程问答-------------------- IDKey nvarchar 64
ObjectiveType nvarchar 100
ObjectiveID nvarchar 64
AttachAddr nvarchar 225
AttachName nvarchar 255
UploadTime datetime 8
AttachSize bigint 8
DateOfExpire datetime 8
OrderID bigint 8
vTP timestamp 8

我的表结构差不多是这样的 --------------------编程问答-------------------- 上传:


private void AddAttachment()
{
if(Session[(string)ViewState["AttachmentDataTableName"]]==null)
{
((PageBase)Page).RedirectToDefaultErrorPage("SessionTimeOut","Session[tblAttachment]");
}
DataTable tblAttachment=(DataTable)Session[(string)ViewState["AttachmentDataTableName"]];

try
{

//string absolutepath=Request.PhysicalApplicationPath;

//string path =Path.Combine(absolutepath,ConfigurationSettings.AppSettings["SavefilePath"]);

//string path = Common.CEncryptDecrypt.Decrypt3DES(ConfigurationSettings.AppSettings["SavefilePath"],_sStrKey);

string path = ConfigurationSettings.AppSettings["SavefilePath"];

string IDKey=System.Guid.NewGuid().ToString();

string subFolderName=ModuleID+"/"+DateTime.Now.ToString("yyyyMMddHHmmssfff").Substring(0,6);

path=Path.Combine(path,subFolderName);

//old file name
string oldFileName= Path.GetFileName(uplTheFile.PostedFile.FileName);
//extension name
string extension=Path.GetExtension(uplTheFile.PostedFile.FileName);

string newFileName=IDKey+extension;


if(!Directory.Exists(path))
{
Directory.CreateDirectory (path);
}

if(this.uplTheFile.PostedFile !=null && this.uplTheFile.PostedFile.FileName !=null && this.uplTheFile.PostedFile.FileName.Length>0)
{
uplTheFile.PostedFile.SaveAs(Path.Combine(path,newFileName)); 
              
DataRow dr=tblAttachment.NewRow ();
dr["IDKey"]=IDKey;
//dr["ModuleID"]=ModuleID;
dr["AttachName"]=oldFileName;
dr["ObjectiveType"]=this.ModuleID;
dr["ObjectiveID"]=InfoID.Trim();
//dr["AttachAddr"]=path;
dr["AttachAddr"]=subFolderName;
dr["UploadTime"]=System.DateTime.Now;
dr["AttachSize"]=uplTheFile.PostedFile.ContentLength;
if(this.DateEditor1.Value == null||this.DateEditor1.Value.Length==0)
{
}
else
{
dr["DateOfExpire"]=this.DateEditor1.Value;
}

tblAttachment.Rows.Add (dr);
this.BindAttachmentList() ;
this.DateEditor1.Value = "";
}

}
catch(Exception exp)
{

this.DisplayError(exp.Message);
return;
}


} --------------------编程问答-------------------- 能不能写的详细一点啊....谢了 --------------------编程问答-------------------- 呵呵  我也做这个 好愁啊 --------------------编程问答-------------------- 实现ASP.NET中FileUpload多文件上传

这里附加一下上易做图个文件的CS代码:

protected void upload_Click(object sender, EventArgs e)
    {

        if (upfile.HasFile)
        {
            string fname = upfile.PostedFile.FileName;
            int fi = fname.LastIndexOf("//") + 1;
            string filename = fname.Substring(fi);
            upfile.PostedFile.SaveAs(Server.MapPath("upload//" + filename));
            Response.Write("<script>alert('报名表上传成功!');</script>");
        }
        else
        {
            Response.Write("<script>alert('请选择您要上传的报名表!');</script>");
        }

    }

下面是上传多个文件的全部代码,第一次实现这样的功能,难免有考虑不周全的地方,还望高手见到后指教!

【显示页面代码】:

在<head></head>标签中插入如下脚本代码:

<script type="text/javascript">
         function addfile()
         {
          var uploadfiles=document.getElementById("uploadfiles"),str = '<INPUT type="file" size="50" NAME="File">';
          uploadfiles.innerHTML+=str;
         }
</script>

在页面主体部分插入:

<div>
     <p id="uploadfiles"><input type="file" size="50" name="file"></p>
     <input onclick="addfile()" type="button" value="增加">
     <asp:button id="uploadbutton" Text="开始上传" Runat="server"></asp:button>
</div>

【C#代码】:

添加using指令:using System.Text.RegularExpressions;

在protected void Page_Load(object sender, EventArgs e){}中插入如下代码:

HttpFileCollection files = HttpContext.Current.Request.Files;
        //状态信息
        System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
        for (int ifile = 0; ifile < files.Count; ifile++)
        {
            HttpPostedFile postedfile = files[ifile];
            string filename, fileExt;
            filename = System.IO.Path.GetFileName(postedfile.FileName);    //获取文件名
            fileExt = System.IO.Path.GetExtension(filename);    //获取文件后缀

            int MaxAllowUploadFileSize = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["MaxAllowUploadFileSize"]);     //定义允许上传文件大小
            if (MaxAllowUploadFileSize == 0) { MaxAllowUploadFileSize = 26500; }
            string allowexts = System.Configuration.ConfigurationSettings.AppSettings["AllowUploadFileType"];    //定义允许上传文件类型
            if (allowexts == "") { allowexts = "doc|docx|rar|xls|xlsx|txt"; }
            Regex allowext = new Regex(allowexts);

            if (postedfile.ContentLength < MaxAllowUploadFileSize && allowext.IsMatch(fileExt)) //检查文件大小及扩展名
            {
                postedfile.SaveAs(Server.MapPath("upload//" + filename + fileExt));    //upload为与本页面同一目录,可自行修改
            }
            else
            {
                Response.Write("<script>alert('不允许上传类型" + fileExt + "或文件过大')</script>");
            }
        }

【Web.config中代码】:

<appSettings>
    <add key="MaxAllowUploadFileSize" value="256000" />
    <add key="AllowUploadFileType" value="doc|docx|rar|xls|xlsx|txt" />
</appSettings>
--------------------编程问答-------------------- 刚好我做过了 等下贴 --------------------编程问答-------------------- aspx页面

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="UpLoad.aspx.cs" Inherits="Asiastar.NR.FileOperation.UpLoad" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>上传文件</title>
    <link href="../CSS/common.css" rel="stylesheet" type="text/css" />
    <link href="../CSS/table.all.css" rel="stylesheet" type="text/css" />
    <link href="../CSS/ret_style.css" rel="stylesheet" type="text/css" />
    <link href="../CSS/dtree.css" rel="stylesheet" type="text/css" />

    <script src="../js/jquery-1.3.2.js" type="text/javascript"></script>

    <script src="../js/jquery-1.3.2-vsdoc2.js" type="text/javascript"></script>

    <script src="../js/jquery-1.3.2.min.js" type="text/javascript"></script>

    <link href="../CSS/Table.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        #Decription {
            width: 350px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server" method="post" enctype="multipart/form-data">
    <input id="method" type="hidden" name="method" />
    <input id="Hidden1" type="hidden" name="FunName" />
    <input id="decrition" type="text" value="资源说明" onfocus="cls()" onblur="res()" runat="server"
        name="decrition" /><br />
    <div id="_container">
        <input type="file" size="50" name="File" id="file" />
        <input id="Button1" type="button" value="上传" onclick="test()" size="50" /></div>
    <div>
        <input type="button" value="添加文件" onclick="FN_addFile()" style="width: 93px; height: 23px" />
    </div>
    <div style="padding: 10px 0">
    </div>
    <div>
        <asp:Label ID="strStatus" runat="server" Font-Names="宋体" Font-Bold="True" Font-Size="9pt"
            Width="500px" BorderStyle="None" BorderColor="White"></asp:Label>
    </div>
    </form>
</body>

<script type="text/javascript">
            function FN_addFile() {
                var div = document.createElement("div");
                var f = document.createElement("input");
                f.setAttribute("type", "file")
                f.setAttribute("name", "File")
                f.setAttribute("size", "50")
                div.appendChild(f)
                var d = document.createElement("input");
                d.setAttribute("type", "button")
                d.setAttribute("onclick", "FN_deteFile(this)");
                d.setAttribute("value", "移除")
                div.appendChild(d)
                document.getElementById("_container").appendChild(div);
            }
            function FN_deteFile(o) {
                while (o.tagName != "DIV")o = o.parentNode;
                o.parentNode.removeChild(o);
            }
            
            function cls(){ 
                //捕获触发事件的对象,并设置为以下语句的默认对象 
                with(event.srcElement) 
                     //如果当前值为默认值,则清空 
                if(value==defaultValue) value="" 
                } 
                function res(){ 
                //捕获触发事件的对象,并设置为以下语句的默认对象 
                with(event.srcElement) 
                //如果当前值为空,则重置为默认值 
                if(value=="") value=defaultValue 
          }
          
          function test()
          {
             document.getElementById("method").value = "Upload";
             form1.submit();
          }
          
          function FN_AjaxUpload()
          {
            $.ajax({
            type:"post",//请求方式
            url:"../ajax/AjaxUploadFiles.ashx",//载入页面的URL地址
            data:{decrition:$("#decrition").val()},
            success:function(data){//返回成功的函数
            if(data =="1"){
            alert('上传成功');
            }else if(data =="0")
            {
            alert('文件已经存在!');
            }else
            {alert('上传失败');}
            }
            });
          }
          
          
        
</script>

</html>


--------------------编程问答-------------------- .cs页面

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.IO;
using Asiastar.NRModel;
using Asiastar.NRBLL;

namespace Asiastar.NR.FileOperation
{
    public partial class UpLoad : System.Web.UI.Page
    {
        public string method = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["username"] == null)
            {
                Response.Redirect("../Login/Login.aspx");
            }
            method = Request.Form["method"];
            if (!string.IsNullOrEmpty(method) && method.Equals("Upload"))
            {
                FN_UpFiles();
            }
        }
        //上传文件
        public void FN_UpFiles()
        {
            //遍历File表单元素
            HttpFileCollection files = HttpContext.Current.Request.Files;
            //StringBuilder strMsg = new StringBuilder();
            //strMsg.Append("上传的文件分别是:<hr color='pink'/>");
            try
            {
                for (int iFile = 0 ; iFile < files.Count ; iFile++)
                {
                    //检查文件扩展名字
                    HttpPostedFile postedFile = files[iFile];
                    string fileName = "";
                    //string fileExtension = "";
                    fileName = Path.GetFileName(postedFile.FileName);
                    if (fileName != "")
                    {
                        try
                        {
                            string strpath = HttpContext.Current.Request.MapPath("~/ResourcesFolder/") + fileName;
                            if (System.IO.File.Exists(strpath))
                            {
                                Response.Write("已经存在文件:" + fileName + "<br>");
                            }
                            else
                            {
                                try
                                {
                                    NRModel.File model = new NRModel.File();
                                    NRBLL.File bf = new NRBLL.File();
                                    Guid guid1 = Guid.NewGuid();
                                    Guid guid2 = Guid.NewGuid();
                                    Guid guid3 = Guid.NewGuid();
                                    Guid guid4 = Guid.NewGuid();
                                    model.Fileid = guid1;
                                    model.Folderid = guid2;
                                    model.Filepath = strpath;
                                    model.FileNam = fileName.ToString();
                                    model.FileSize = postedFile.ContentLength;
                                    model.Decription = this.decrition.Value;
                                    model.CreateOn = DateTime.Now;
                                    model.CreateBy = guid3;
                                    model.ModefyBy = guid4;
                                    if (bf.FN_AddNewRes(model) > 0)
                                    {
                                        //fileExtension = Path.GetExtension(fileName);
                                        //strMsg.Append("上传的文件类型:" + postedFile.ContentType.ToString() + "<br>");
                                        //strMsg.Append("客户端文件地址:" + postedFile.FileName + "<br>");
                                        //strMsg.Append("上传文件的文件名:" + fileName + "<br>");
                                        //strMsg.Append("上传文件的扩展名:" + fileExtension + "<br>");
                                        //strMsg.Append("上传文件的大小:" + postedFile.ContentLength.ToString() + "个字节" + "<br>");
                                        postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("~/ResourcesFolder/") + fileName);
                                        Page.RegisterStartupScript("提示", "<script language='javascript'>alert('上传成功!')</script>");
                                        Response.Write("<script language='javascript'>self.opener.location.reload();</script>");
                                        Response.Write("<script language='javascript'>window.close();</script>");
                                    }
                                }
                                catch (Exception ex)
                                {
                                    NR.Error.ErrHandler.WriteError(ex.ToString());
                                }

                            }

                        }
                        catch (Exception ex)
                        {
                            NR.Error.ErrHandler.WriteError(ex.ToString());
                        }
                    }
                    else
                    {
                        throw new Exception("上传出错");
                    }
                }
                //strStatus.Text = strMsg.ToString();
            }
            catch (System.Exception ex)
            {
                NR.Error.ErrHandler.WriteError(ex.ToString());
            }
        }
        //public void CreateEventLog(string FilePath, string EventMessage)
        //{
        //    try
        //    {
        //        StringBuilder strTemp = new StringBuilder();

        //        string CreateFileName = FilePath + "\\ " + DateTime.Now.ToString("yyyyMMddhhmmss ") + ".txt ";
        //        //***创建一个文件 
        //        FileInfo mFileInfo = new FileInfo(CreateFileName);

        //        StreamWriter sw = mFileInfo.AppendText();

        //        sw.Write(EventMessage);

        //        //***关闭写入文件流 
        //        sw.Close();
        //    }
        //    catch (Exception ex)
        //    {

        //        CreateEventLog(@"c:", ex.ToString());
        //    }

        //}

    }
}


补充:.NET技术 ,  ASP.NET
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,