開始通過固定代碼刪除SQL Injection vulnerability:
FileUrl = "C:\\Attachments\\" + Path.GetFileName(UploadCtrl.NavigateUrl);
using (SqlConnection conn = new SqlConnection(SQLSrc.ConnectionString))
using (SqlCommand command = conn.CreateCommand())
{
command.CommandText = "insert into Attachments values (@FileName, @MimeType, @FileBytes)";
command.Parameters.AddWithValue("@FileName", Path.GetFileName(FileUrl));
command.Parameters.AddWithValue("@MimeType", MIME(Path.GetExtension(Att_Overview_Link.NavigateUrl)));
command.Parameters.AddWithValue("@FileBytes", File.ReadAllBytes(FileUrl));
conn.Open();
command.ExecuteNonQuery();
}
注:我不知道你的UploadCtrl
是什麼,但大多數的文件上傳控件,得到作爲Stream
直接訪問上傳的文件,而不是服務器上的文件名。根據特定控件的工作方式,您可能需要更改讀取上傳文件的方式。
要恢復的文件,你會選擇相關的名稱,MIME類型和字節,並將其寫入響應:
using (SqlConnection conn = new SqlConnection(SQLSrc.ConnectionString))
using (SqlCommand command = conn.CreateCommand())
{
command.CommandText = "SELECT FileName, MimeType, FileBytes FROM Attachments WHERE PK = @PK";
command.Parameters.AddWithValue("@PK", Request.QueryString["pk"]);
conn.Open();
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.CloseConnection))
{
if (reader.Read())
{
string name = reader.GetString(reader.GetOrdinal("FileName"));
Response.AppendHeader("Content-Disposition", "attachment; filename=" + name);
Response.ContentType = reader.GetString(reader.GetOrdinal("MimeType"));
int startIndex = 0;
byte[] buffer = new byte[4096];
int fieldIndex = reader.GetOrdinal("FileBytes");
int bytesRead = (int)reader.GetBytes(fieldIndex, startIndex, buffer, 0, buffer.Length);
while (bytesRead != 0)
{
Response.OutputStream.Write(buffer, 0, bytesRead);
Response.Flush();
startIndex += bytesRead;
bytesRead = (int)reader.GetBytes(fieldIndex, startIndex, buffer, 0, buffer.Length);
}
}
}
}
你的代碼是容易[SQL注入](HTTP:// WWW。 troyhunt.com/2013/07/everything-you-wanted-to-know-about-sql.html)。改用參數化查詢。 –