Kürzlich gab es einen Job im Zusammenhang mit E-Mails, bei dem Dateien in eine Datenbank hochgeladen, die Dateien dann aus der Datenbank gelesen und heruntergeladen werden mussten.
Ich habe einige Informationen gefunden und auf das Projekt angewendet.
Der Aufbau der Datenbank ist wie folgt:
VERWENDEN[EOffice]
GEHEN
/**//****** Objekt: Tabelle [dbo].[Group_Files] Skriptdatum: 20.07.2006 23:57:34 ******/
SETZEN SIE ANSI_NULLS AUF
GEHEN
SETZEN SIE QUOTED_IDENTIFIER EIN
GEHEN
SETZEN SIE ANSI_PADDING EIN
GEHEN
TABELLE ERSTELLEN [dbo].[Group_Files](
[ID] [int] IDENTITY(1,1) NOT NULL,
[FileName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Group_Files_FileName] DEFAULT (''),
[FileBody] [Bild] NULL,
[FileType] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT [DF_Group_Files_FileType] DEFAULT (''),
CONSTRAINT [PK_Group_Files] PRIMARY KEY CLUSTERED
(
[ID]ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMÄR]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SETZEN SIE ANSI_PADDING AUS
Dann habe ich eine gespeicherte Prozedur mit dem folgenden Code geschrieben:
VERWENDEN[EOffice]
GEHEN
/**//****** Objekt: StoredProcedure [dbo].[SendTo_Group_Email] Skriptdatum: 20.07.2006 23:59:21 ******/
SETZEN SIE ANSI_NULLS AUF
GEHEN
SETZEN SIE QUOTED_IDENTIFIER EIN
GEHEN
Erstellen Sie PROCEDURE [dbo].[SendTo_Group_Email]
(
@Title varchar(200),
@Content varchar(MAX),
@Area varchar(max),
@Sender varchar(50),
@Dept varchar(50),
@SendToUser varchar(50),
@FileName varchar(200),
@FileBody-Bild,
@FileType varchar(4)
)
AS
INSERT Group_Email (Title,[Content],Area,SendToUser,Dept,Sender,FileName,FileBody,FileType) VALUES (@Title,@Content,@Area,@SendToUser,@Dept,@Sender,@FileName,@FileBody, @FileType)
Der Programmcode lautet wie folgt:
SendEmail.aspx
1<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SendEmail.aspx.cs" Inherits="GroupWork_SendEmail" %>
2
3<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
4
5<html xmlns=" http://www.w3.org/1999/xhtml " >
6
7<head runat="server">
8 <title>E-Mail senden</title>
9<meta http-equiv="Content-Type" content="text/html; charset=utf-8"><style type="text/css">
10body,td,th {
11 Schriftgröße: 9pt;
12}
13body {
14 Hintergrundbild: url();
15 Hintergrundfarbe: #F2F7FB;
16 Rand links: 10px;
17 Rand oben: 5px;
18 Rand rechts: 10px;
19 Rand unten: 5px;
20}
21-->
22</style></head>
23<script language="vbscript">
24Funktion Select_Local_User(URL)
25 dim k
26 k=showModalDialog(url,"","dialogWidth:485px;status:no;dialogHeight:280px")
27 wenn ubound(split(k," $#@&!"))>=0 dann
28 document.form1.HiddenField1.value = split(k," $#@&!")(0 )
29 document.form1.txtLocalUser.value = split(k," $#@&!")(1 )
30 Ende wenn
31end-Funktion
32
33Funktion Select_Remote_User(URL)
34 dim k
35 k=showModalDialog(url,"","dialogWidth:485px;status:no;dialogHeight:310px")
36 wenn ubound(split(k," $#@&!"))>=0 dann
37 document.form1.HiddenField2.value = split(k," $#@&!")(0 )
38 document.form1.txtRemoteUser.value=split(k," $#@&!")(1 )
39 Ende wenn
40end-Funktion
41
42</script>
43<Körper>
44 <form id="form1" method="post" enctype="multipart/form-data" runat="server">
45 <div style="text-align: center">
46 <table border="0" cellpadding="0" cellpacing="0" width="100%">
47 <tr>
48 <td width="1%"><img src="../Images/spacer.gif" width="11" height="1" border="0" alt="" /></td>
49 <td colspan="2"><img src="../Images/spacer.gif" width="209" height="1" border="0" alt="" /></td>
50 <td width="1%"><img src="../Images/spacer.gif" width="12" height="1" border="0" alt="" /></td>
51 <td width="2%"><img src="../Images/spacer.gif" width="1" height="1" border="0" alt="" /></td>
52 </tr>
53 <tr>
54 <td style="height: 35px"><img src="../Images/ye_r1_c1.gif" alt="" name="ye_r1_c1" width="11" height="30" border="0" id ="ye_r1_c1" /></td>
55 <td colspan="2" align="left" background="../images/ye_r1_c2.gif" style="height: 35px"><table width="119" border="0" cellpacing="0" cellpadding="0">
56 <tr>
57 <td width="40" height="20"> </td>
58 <td width="79" valign="top"><strong>Für Erhalt registrieren</strong></td>
59 </tr>
60 </table></td>
61 <td style="height: 35px"><img src="../Images/ye_r1_c3.gif" alt="" name="ye_r1_c3" width="12" height="30" border="0" id ="ye_r1_c3" /></td>
62 <td style="height: 35px"></td>
63 </tr>
64 <tr>
65 <td background="../images/ye_r2_c1.gif"> </td>
66 <td width="13%"> </td>
67 <td width="83%" align="left"><img src="../Images/dj.gif" width="300" height="30" /></td>
68 <td background="../images/ye_r2_c3.gif"> </td>
69 <td> </td>
70 </tr>
71 <tr>
72 <td background="../images/ye_r2_c1.gif"> </td>
73 <td colspan="2"><div align="center">
74 <table border="0" cellpadding="0" cellpacing="1" bgcolor="#CCCCCC" style="width: 566px">
75 <tr bgcolor="#b9d5f4">
76 <td style="width: 186px; height: 20px">
77 <div align="center" class="style2">Dateititel</div></td>
78 <td colspan="2" align="left" style="height: 20px; width: 433px;">
79 <asp:TextBox ID="txtTitle" runat="server" class="Input_TextBox" Width="277px"></asp:TextBox>
80 <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtTitle"
81 Display="Dynamic" ErrorMessage="Dateititel darf nicht leer sein."></asp:RequiredFieldValidator></td>
82 </tr>
83 <tr bgcolor="#F1F5FC">
84 <td style="width: 186px; height: 20px">
85 lokale Benutzer</td>
86 <td align="left" colspan="2" style="width: 433px; height: 20px">
87 <asp:TextBox ID="txtLocalUser" runat="server" Breite="279px"></asp:TextBox><input
88 id="SelectLocal" class="Input_Button" name="SelectLocal" onClick="vbscript:Select_Local_User('..SelectMulti.aspx')" type="button"
89 value="select" /><asp:HiddenField ID="HiddenField1" runat="server" />
90 </td>
91 </tr>
92 <tr bgcolor="#b9d5f4">
93 <td style="width: 186px; height: 20px">
94 Remote-Benutzer</td>
95 <td align="left" colspan="2" style="width: 433px; height: 20px">
96 <asp:TextBox ID="txtRemoteUser" runat="server" Breite="279px"></asp:TextBox>
97 <input id="SelectRemote" class="Input_Button" name="SelectRemote" onClick="vbscript:Select_Remote_User('..SelectRemoteUser.aspx')"
98 type="button" value="select" />
99 <asp:HiddenField ID="HiddenField2" runat="server" />
100 </td>
101 </tr>
102 <tr bgcolor="#F1F5FC">
103 <td rowspan="2" align="center" style="width: 186px; height: 11px;"> Datei hochladen</td>
104 <td colspan="2" rowspan="2" align="left" valign="top" bgcolor="#F1F5FC" style="width: 433px; height: 11px;">
105 <input id="File1" runat="server" style="width: 381px" type="file" /><br />
106 <input id="File2" runat="server" style="width: 379px" type="file" />
107 <input id="File3" runat="server" style="width: 379px" type="file" />
108 <input id="File4" runat="server" style="width: 379px" type="file" />
109 <input id="File5" runat="server" style="width: 377px" type="file" /></td>
110 </tr>
111 <tr>
112 </tr>
113 <tr bgcolor="#B9D5F4">
114 <td style="width: 186px; height: 22px;">
115 <div align="center" class="style2">E-Mail-Inhalt</div></td>
116 <td colspan="2" align="left" style="width: 433px; height: 22px;">
117 <asp:TextBox ID="txtContent" runat="server" Height="57px" TextMode="MultiLine" Width="296px" class="Input_TextBox"></asp:TextBox>
118 <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="txtContent"
119 Display="Dynamic" ErrorMessage="Der E-Mail-Inhalt darf nicht leer sein."></asp:RequiredFieldValidator></td>
120 </tr>
121 <tr bgcolor="#F1F5FC">
122 <td style="width: 186px; height: 6px">
123 </td>
124 <td colspan="2" align="left" style="height: 6px; width: 433px;">
125 <asp:CheckBox ID="chkSms" runat="server" Text="SMS Notification" />
126 <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Submit" class="Input_Button" />
127 <input type="reset" name="Submit" value="Reset" class="Input_Button" /></td>
128 </tr>
129 </table>
130 </div></td>
131 <td background="../images/ye_r2_c3.gif"> </td>
132 <td> </td>
133 </tr>
134 <tr>
135 <td><img src="../Images/ye_r3_c1.gif" alt="" name="ye_r3_c1" width="11" height="22" border="0" id="ye_r3_c1" />< /td>
136 <td colspan="2" background="../images/ye_r3_c2.gif"> </td>
137 <td><img src="../Images/ye_r3_c3.gif" alt="" name="ye_r3_c3" width="12" height="22" border="0" id="ye_r3_c3" />< /td>
138 <td> </td>
139 </tr>
140 </table>
141 </div>
142 </form>
143</body>
144</html>
145
SendEmail.aspx.cs
1System verwenden;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5mit System.Web;
6mit System.Web.Security;
7mit System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12using System.Data;
13using System.Data.SqlClient;
14mit EOffice.Model;
15mit EOffice.SqlServer;
16mit System.IO;
17using System.Configuration;
18
19//iWebSMS2000 verwenden;
20[Serialisierbar]
21öffentliche Teilklasse GroupWork_SendEmail: System.Web.UI.Page
zweiundzwanzig{
23 öffentliche SqlConnection-Verbindung;
24 //öffentliche iSMS2000 SMS;
25 //public DBstep.SMSClient2000 ObjiSMSClient2000;
26 protected void Page_Load(object sender, EventArgs e)
27 {
28 conn = new SqlConnection("SERVER=SERVER;UID=sa;PWD=8860;database=EOFFICE_SERVER;");
29
30}
31 protected void btnSubmit_Click(object sender, EventArgs e)
32 {
33 String strTitle = txtTitle.Text;
34 String strContent = txtContent.Text;
35 UserInfo info = (UserInfo)Session["EOfficeUserInfo"];
36 String strUserName = info.UserName;
37 String strTmpDept = info.DeptId.ToString();
38
39 String strUnitName = ConfigurationSettings.AppSettings["UnitName"];
40 String strServerFileIndex = ""; //Serverseitiger Dateianhangsindex
41 String strClientFileIndex = ""; //Client-Dateianhangsindex
42
43 String strRemote = HiddenField2.Value;
44 String[] strRemoteUser = strRemote.Split(',');
45 String strTmpUserName;
46 String strTmpServer;
47 Boolean bDone = false;
48
49 /**/////////Mehrere Anhangscodes hochladen//////////////
50 //Das File-Formularelement abrufen
51 HttpFileCollection files = HttpContext.Current.Request.Files;
52 HttpPostedFilepostedFile;
53
54 foreach (String strUser in strRemoteUser)
55 {
56 String[] strSplit = strUser.Split('/');
57 strTmpUserName = strSplit[0];
58 strTmpServer = strSplit[1];
59 String strConnectString = "";
60 String strAreaName = "";
61 int nAreaID = 0;
62 String strDept = "";
63 strClientFileIndex = "";
64 SqlConnection connClient;
65
66 String strSQL = "Select * From Area Where AreaCode='" + strTmpServer + "'";
67 SqlCommand cmd = new SqlCommand(strSQL, conn);
68 cmd.Connection.Open();
69 mit (SqlDataReader sdr = cmd.ExecuteReader())
70 {
71 if (sdr.Read())
72 {
73 strConnectString = sdr["ConnectString"].ToString();
74 strAreaName = sdr["AreaName"].ToString();
75 nAreaID = Convert.ToInt16(sdr["ID"]);
76 }
77 }
78 cmd.Connection.Close();
79
80 strSQL = "Select * From MemberList Where UserName='" + strTmpUserName + "' And AreaID=" + nAreaID;
81 cmd = new SqlCommand(strSQL, conn);
82 cmd.Connection.Open();
83 mit (SqlDataReader sdr = cmd.ExecuteReader())
84 {
85 if (sdr.Read())
86 {
87 strDept = sdr["Dept"].ToString();
88 }
89 }
90 cmd.Connection.Close();
91
92 connClient = new SqlConnection(strConnectString);
93
94 for (int intCount = 0; intCount < files.Count; intCount++)
95 {
96postedFile = files[intCount];
97
98 if (postedFile.ContentLength > 0)
99 {
100 String strOldFilePath =postedFile.FileName;
101 String strFileName = strOldFilePath.Substring(strOldFilePath.LastIndexOf("\") + 1);
102
103 //Dateien auf den Server hochladen
104 //File1.PostedFile.SaveAs("c:\Test\" + DateTime.Now.ToString("yyyyMMddhhmmss") + strExtension);
105
106 //Wird zum Speichern der Dateigröße verwendet
107 int intDocLen;
108 //Stream wird zum Lesen hochgeladener Daten verwendet
109 Stream objStream;
110 String strDocExt;
111 //Laden Sie den spezifischen Inhalt der Datei hoch
112 intDocLen =postedFile.ContentLength;
113 strDocExt = strOldFilePath.Substring(strOldFilePath.LastIndexOf(".") + 1);
114
115 byte[] Docbuffer = new byte[intDocLen];
116 objStream =postedFile.InputStream;
117
118
119 //Datei im Cache speichern
120
121 //Der Cache wird in der Datenbank gespeichert
122 objStream.Read(Docbuffer, 0, intDocLen);
123
124 string fileType =postedFile.ContentType;
125
126
127 //Führen Sie die serverseitig gespeicherte Prozedur Send_Group_Email aus
128 if (!bDone)
129 {
130 cmd = new SqlCommand("Send_Group_Email", conn);
131 cmd.CommandType = CommandType.StoredProcedure;
132 cmd.Parameters.Add("@FileName", SqlDbType.VarChar, 200);
133 cmd.Parameters.Add("@FileBody", SqlDbType.Image);
134 cmd.Parameters.Add("@FileType", SqlDbType.VarChar, 4);
135 cmd.Parameters.Add("@File_Index", SqlDbType.Int);
136
137 cmd.Parameters[0].Value = strFileName;
138 cmd.Parameters[1].Value = Docbuffer;
139 //cmd.Parameters[2].Value = strDocExt;]
140 cmd.Parameters[2].Value = fileType;
141
142 //cmd.Parameters.Add(new SqlParameter("@File_Index", SqlDbType.Int));
143 cmd.Parameters[3].Direction = ParameterDirection.ReturnValue;
144 cmd.Connection.Open();
145 cmd.ExecuteNonQuery();
146 strServerFileIndex += cmd.Parameters[3].Value.ToString() + ",";
147 cmd.Connection.Close();
148 }
149
150 //Gespeicherte Client-Prozedur Get_Upload_File ausführen
151 cmd = new SqlCommand("Get_Upload_File", connClient);
152 cmd.CommandType = CommandType.StoredProcedure;
153 cmd.Parameters.Add("@FileName", SqlDbType.VarChar, 200);
154 cmd.Parameters.Add("@FileBody", SqlDbType.Image);
155 cmd.Parameters.Add("@FileType", SqlDbType.VarChar, 4);
156 cmd.Parameters.Add("@File_Index", SqlDbType.Int);
157
158 cmd.Parameters[0].Value = strFileName;
159 cmd.Parameters[1].Value = Docbuffer;
160 //cmd.Parameters[2].Value = strDocExt;
161 cmd.Parameters[2].Value = fileType;
162
163 //cmd.Parameters.Add(new SqlParameter("@File_Index", SqlDbType.Int));
164 cmd.Parameters[3].Direction = ParameterDirection.ReturnValue;
165 cmd.Connection.Open();
166 cmd.ExecuteNonQuery();
167 strClientFileIndex += cmd.Parameters[3].Value.ToString() + ",";
168 cmd.Connection.Close();
169 }
170
171 if (intCount.Equals(files.Count - 1))
172 {
173 bDone = true;
174 }
175 }
176
177 strClientFileIndex = strClientFileIndex.Remove(strClientFileIndex.Length - 1);
178
179 strSQL = "In Group_Email einfügen (Title,Content,Area,SendToUser,Dept,Sender,Files_Index)";
180 strSQL += " Werte (";
181 strSQL += "'" + strTitle + "',";
182 strSQL += "'" + strContent + "',";
183 strSQL += "'" + strUnitName + "',";
184 strSQL += "'" + strTmpUserName + "',";
185 strSQL += "'" + strDept + "',";
186 strSQL += "'" + strUserName + "',";
187 strSQL += "'" + strClientFileIndex + "')";
188 cmd = new SqlCommand(strSQL, connClient);
189 cmd.Connection.Open();
190 cmd.ExecuteNonQuery();
191 cmd.Connection.Close();
192
193 String strTmpServerFileIndex = strServerFileIndex.Remove(strServerFileIndex.Length - 1);
194
195 strSQL = "Einfügen in Group_Email_Sever (Title,Content,Area,SendToUser,Dept,Sender,Files_Index)";
196 strSQL += " Werte (";
197 strSQL += "'" + strTitle + "',";
198 strSQL += "'" + strContent + "',";
199 strSQL += "'" + strAreaName + "',";
200 strSQL += "'" + strTmpUserName + "',";
201 strSQL += "'" + strTmpDept + "',";
202 strSQL += "'" + strUserName + "',";
203 strSQL += "'" + strTmpServerFileIndex + "')";
204 cmd = new SqlCommand(strSQL, conn);
205 cmd.Connection.Open();
206 cmd.ExecuteNonQuery();
207 cmd.Connection.Close();
208 }
209 /**/////////Hochladen mehrerer Anhänge beenden//////////////
210 Response.Redirect("../SuccessMsg.aspx");
211 }
212}
213
Code zum Herunterladen der Datei:
DownFile.aspx
DownFile.aspx.cs
1System verwenden;
2using System.Data;
3using System.Configuration;
4using System.Collections;
5mit System.Web;
6mit System.Web.Security;
7mit System.Web.UI;
8using System.Web.UI.WebControls;
9using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11
12using System.Data;
13using System.Data.SqlClient;
14mit EOffice.Model;
15mit EOffice.SqlServer;
16mit System.IO;
17
18[Serialisierbar]
19öffentliche Teilklasse GroupWork_DownFile: System.Web.UI.Page
20{
21 öffentliche SqlConnection-Verbindung;
22 public String strFileID;
23 öffentliche UserInfo-Informationen;
24 protected void Page_Load(object sender, EventArgs e)
25 {
26 strFileID = Request.QueryString["ID"];
27 info = (UserInfo)Session["EOfficeUserInfo"];
28
29 if (strFileID == null)
30 {
31 Response.Redirect("../ErrorMsg.aspx");
32}
33
34 DbLink db = new DbLink();
35 conn = db.Connect();
36
37 String strSQL = "Select * From Group_Files Where ID=" + strFileID; //+ " And SendToUser = '" + info.UserName + "'";
38 SqlCommand cmd = new SqlCommand(strSQL, conn);
39 cmd.Connection.Open();
40 mit (SqlDataReader sdr = cmd.ExecuteReader())
41 {
42 if (!sdr.Read())
43 {
44 Response.Redirect("../ErrorMsg.aspx");
45 }
46 sonst
47 {
48 Response.Clear();
49 String strFileName = sdr["FileName"].ToString();
50 Response.ContentType = "APPLICATION/OCTET-STREAM";
51 Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName));
52 Response.Buffer = true;
53 Response.BinaryWrite((byte[])sdr["FileBody"]);
54
55 //Response.Clear();
56 //Response.ContentType = "application/octet-stream";
57 /**/////Response.AddHeader("Content-Type", sdr["FileType"].ToString());
58 //Response.BinaryWrite((byte[])sdr["FileBody"]);
59 }
60 }
61 //conn.Close();
62
63 /**//*
64 SqlDataAdapter da = new SqlDataAdapter(strSQL, conn);
65 SqlCommandBuilder MyCB = new SqlCommandBuilder(da);
66 DataSet ds = new DataSet("MyImages");
67 byte[] MyData = neues Byte[0];
68 da.Fill(ds, "MyImages");
69 DataRow myRow = ds.Tables["MyImages"].Rows[0];
70 String strFileName = Convert.ToString(myRow["FileName"]);
71 MyData = (byte[])myRow["FileBody"];
72 int ArraySize = new int();
73 ArraySize = MyData.GetUpperBound(0);
74 FileStream fs = new FileStream(@"C:\Download" + strFileName,
75 FileMode.OpenOrCreate, FileAccess.Write);
76 fs.Write(MyData, 0, ArraySize);
77 fs.Close();
78 */
79 //Response.Write("Download file" + strFileName + "Success!");
80}
81}
82