• Познакомьтесь с пентестом веб-приложений на практике в нашем новом бесплатном курсе

    «Анализ защищенности веб-приложений»

    🔥 Записаться бесплатно!

  • CTF с учебными материалами Codeby Games

    Обучение кибербезопасности в игровой форме. Более 200 заданий по Active Directory, OSINT, PWN, Веб, Стеганографии, Реверс-инжинирингу, Форензике и Криптографии. Школа CTF с бесплатными курсами по всем категориям.

как получить Id файла, который только загрузили в базу Sql

  • Автор темы Kreol
  • Дата начала
K

Kreol

Здраствуйте, аозник вопросик с SQL в C#
Пытаюсь разобраться с FileUpload. Суть проги берем файл рисунка из FU, по нажатию кнопочки отображаем его на страничке, при этом производим запись в БД. А вопросик возник в том, как получить id этого рисунка, который только что загрузили в базу, для того чтобы его сразу же вывести, в соседнем поле image и как получить путь этого рисунка из базы.
есть код записи рисунка в базу

Код:
// Writes file to the database
int len = filMyFile.PostedFile.ContentLength;
byte[] pic = new byte[len];
filMyFile.PostedFile.InputStream.Read(pic, 0, len);
// Insert the image and comment into the database
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("insert into im " + "(Picture, Comment)_
values (@pic, @text)", connection);
cmd.Parameters.Add("@pic", pic);
cmd.Parameters.Add("@text", Comment.Text);
cmd.ExecuteNonQuery();
}
finally
{
connection.Close();
}
Посмотреть вложение FU.rar

Буду рад за ответ, спасибо!
 
K

Kreol

а как правильно написать? так?
Код:
cmd.ExecuteScalar();
SqlCommand idfile = new SqlCommand("SELECT SCOPE_IDENTITY()", connection);

И просто посмотреть idfile
 
K

Kreol

пишет Specified cast is not valid.
и при останове все равно id = 0
 
K

Kreol

есть и можно на ты :( аська есть? если да стучи 280811275
 
K

Kreol

так для этого ж и проект прикрепил, там есть бакап на базу
 
K

Kreol

но в принципе работая с таким сервером надо использовать сохраненные процедуры ...
тоесть?

а насчет кода других вариантов быть не может?
 
K

Kreol

он выводит при останове, object id = null

И что-то, я все равно не понимаю, как тогда потом объект перевести в инт?
Ведь нужно будет выташить картинку именно по id???
может нужно так прописать? правда оно тоже не работает :(
Код:
SqlCommand ident = new SqlCommand("SELECT id FROM im WHERE @id=SCOPE_IDENTITY()", connection);
и вопросик, что ему не нравиться

Код:
Warning	1	
'System.Data.SqlClient.SqlParameterCollection.Add(string, object)' is obsolete: 'Add(String parameterName, Object value) has been deprecated. 
Use AddWithValue(String parameterName, Object value). http://go.microsoft.com/fwlink/?linkid=14202'	
C:\WEBB\FU\Default.aspx.cs	86	25	
C:\WEBB\FU\
 
K

Kreol

Может расскажете где я напортачил??? :(
а то просто я уже 3 день пытаюсь что-то с ним сделать ничо не получается
 
K

Kreol

просто пытаюсь разобраться при помощи живых людей, а не простого текста :(
А насчет как действовать, незнаю. Учиться по книгам, тоже не всегда помогает :) в книгах не описаны все решения проблем, которые нужны для решения задач:) поэтому...

добавлено позже:

мда, никогда бы не подумал, что
Код:
decimal id = (decimal)cmd.ExecuteScalar();
string ura = Convert.ToString(id);
TextBox1.Text = ura;
приведет к конвертации decimal в строчку. :)
Учиться нужно много, но к сожалению каждый глупый вопрос, не будет последним, а будет лишь частью большой глупости.

а возможно ли получить уже с данной таблицы полный путь к файлу?
 
K

Kreol

А как сразу же после загрузки в базу сделать так, чтобы можно было считать в
Код:
<asp:Image id="imgDB" runat="server" Visible="False"></asp:Image>

Код:
 connection.Open();
SqlCommand cmd = new SqlCommand("insert into im " + "(Picture, Comment) values (@pic, @text)\n SELECT SCOPE_IDENTITY()", connection);
cmd.Parameters.Add("@pic", pic);
cmd.Parameters.Add("@text", Comment.Text);
decimal idi = (decimal)cmd.ExecuteScalar();
string ura = Convert.ToString(idi);
TextBox1.Text = ura;
Таким образом? или нет		 
//Вывод из базы
MemoryStream stream = new MemoryStream();
SqlCommand command = new SqlCommand("select Picture from im where id=idi", connection);
byte[] image = (byte[])command.ExecuteScalar();
stream.Write(image, 0, image.Length);
Bitmap bitmap = new Bitmap(stream);

за основу беру

Код:
•	using System.Data.SqlClient;
•	using System.Drawing;
•	using System.Data;
•	using System.IO;
using System.Drawing.Imaging;
Код:
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
MemoryStream stream = new MemoryStream ();
SqlConnection connection = new 
SqlConnection (@"server=INDIA\INDIA;database=iSense;uid=sa;pwd=india");
try
{
connection.Open ();
SqlCommand command = new 
SqlCommand ("select Picture from Image", connection);
byte[] image = (byte[]) command.ExecuteScalar ();  
stream.Write (image, 0, image.Length);
Bitmap bitmap = new Bitmap (stream);
Response.ContentType = "image/gif";
bitmap.Save (Response.OutputStream, ImageFormat.Gif);
} 
finally
{
connection.Close ();
stream.Close ();
}
}
но это вывод просто на страничку, а как засунуть это в картинку ? незнаю
 
K

Kreol

так или нет? написал весь код
использовал для примера

Код:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;

namespace PictureHandler
{
public class PictureHandler : IHttpHandler
{
bool IHttpHandler.IsReusable
{
get { return true; }
}
void IHttpHandler.ProcessRequest(HttpContext context)
{
HttpRequest Request = context.Request;
HttpResponse Response = context.Response;

SqlConnection connection1 = new SqlConnection(GetConnectionString());
SqlCommand myCmd = new SqlCommand("SELECT Picture from im where id = @id", connection1);
myCmd.Parameters.Add("@id", empID);
connection1.Open();
SqlDataReader rdr = myCmd.ExecuteReader();
rdr.Read();
Response.ContentType = "image/jpeg";
Response.OutputStream.Write(rdr.GetSqlBinary(0).Value, 0, rdr.GetSqlBinary(0).Length);
Response.End();
rdr.Close();
connection1.Close();
[color=#FF0000]это конечно нада вставлять в .aspx но где и как чего-то я не въехал
//<img src="photo.aspx?id=10">[/color]
}
}

public partial class Hello : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
this.cmdSend.Click += new System.EventHandler(this.cmdSend_Click);
}

// Processes click on our cmdSend button
private void cmdSend_Click(object sender, System.EventArgs e)
{
// Check to see if file was uploaded "Проверить, что адрес не пуст"
if (filMyFile.PostedFile != null)
{
// Get a reference to PostedFile object "Получить ссылку на объект"
HttpPostedFile myFile = filMyFile.PostedFile;

// Get size of uploaded file "Получить размер файла"
int nFileLen = myFile.ContentLength;

// make sure the size of the file is > 0 "Удостоверится, что размер файла > 0"
if (nFileLen > 0)
{

// Allocate a buffer for reading of the file "Подготовить буфер для чтения файла"
byte[] myData = new byte[nFileLen];

// Read uploaded file from the Stream "Прочитать загруженый файл из потока"
myFile.InputStream.Read(myData, 0, nFileLen);

// Create a name for the file to store "Создать название файла для того, чтобы хранить"
string strFilename = Path.GetFileName(myFile.FileName);

// Write data into a file "Записать данные в файл"
WriteToFile(Server.MapPath(strFilename), ref myData);

// Set label's text "Текст ярлыка"
lblInfo.Text =
"Filename: " + strFilename + "<br>" +
"Size: " + nFileLen.ToString() + "<p>";
// Set URL of the the object to point to the file we've just saved
// "Передать путь файла который только что записали"
imgFile.ImageUrl = strFilename;
imgFile.ToolTip = "This file was stored to as file.";
lblText1.Text = imgFile.ImageUrl;
// show the images and text "Показать рисунок и текст"
imgFile.Visible = true;
//imgDB.Visible = true;
lblText1.Visible = true;
//lblText2.Visible = true;

// Writes file to the database
//==============================
// Create a byte[] from the input file
int len = filMyFile.PostedFile.ContentLength;
byte[] pic = new byte[len];
filMyFile.PostedFile.InputStream.Read(pic, 0, len);
// Insert the image and comment into the database
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
SqlCommand cmd = new SqlCommand("insert into im " + "(Picture, Comment) values (@pic, @text)\n SELECT SCOPE_IDENTITY()", connection);
cmd.Parameters.Add("@pic", pic);
cmd.Parameters.Add("@text", Comment.Text);
decimal id = (decimal)cmd.ExecuteScalar();
string ura = Convert.ToString(id);
TextBox1.Text = ura;
}
finally
{
connection.Close();
}
}
}
}
// Writes file to current folder "Записать файл в текущую папку"
private void WriteToFile(string strPath, ref byte[] Buffer)
{
// Create a file "Создать файл"
FileStream newFile = new FileStream(strPath, FileMode.Create);
// Write data to the file "Записать данные к файлу"
newFile.Write(Buffer, 0, Buffer.Length);
// Close file "Закрыть файл"
newFile.Close();
}
// Generates database connection string
private string GetConnectionString()
{
return "Data Source=localhost;Initial Catalog=MayBase;Integrated Security=True";
}
// Reads the name of current web page
private string GetMyName()
{
// Get the script name
string strScript = Request.ServerVariables["SCRIPT_NAME"];
// Get position of last slash
int nPos = strScript.LastIndexOf("/");
// Get everything after slash
if (nPos > -1)
strScript = strScript.Substring(nPos + 1);
return strScript;
}
}
}
 
K

Kreol

просто я не могу так сходу понять как это делать поэтому и прошу помощи, потому что заведомо длать то, что не будет работать как то не очень, а когда уже есть код тогда сижу и разбираюсь куда что идет, ну тольо начальный уровень вообще поэтому чтараюсь что-то делать. Но прошу помощи.
 
K

Kreol

Код:
<configuration>

<system.web>
<httpHandlers>

<!--<add verb="(verbs)" path="(путь к файлу)" type="(полное имя класса,имя сборки)" /> -->

<add verb="*" path="photo.aspx" type="PictureHandler.PictureHandler,PictureHandler" />


</httpHandlers>

<compilation 
defaultLanguage="c#"
debug="true"
/>

<customErrors 
mode="Off" 
/>

</system.web>

</configuration>

<!--QuoteBegin-Kreol+10:04:2007, 14:52 -->
<span class="vbquote">(Kreol @ 10:04:2007, 14:52 )</span><!--QuoteEBegin-->не вижу как получили empID
[snapback]61981" rel="nofollow" target="_blank[/snapback]​
[/quote]

мда сам не вижу, а что это вообще такое? ;)
 
K

Kreol

а где ж empID?
меня просто сбивает то что мне нудно выводить на имейдж, а они выводят на страничку
 
K

Kreol

а можно пример? ;)
я пытался его в имейдж встатвить, он ошибку на синтаксис кидал
 
K

Kreol

то мне как
Код:
HttpRequest empID =
так делать?

или мне decimal id = (decimal)cmd.ExecuteScalar(); объявить как глобальную и встатвить вместо empID
 
K

Kreol

Код:
Configuration Error 
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. 

Parser Error Message: Could not load file or assembly 'PictureHandler' or one of its dependencies. Не удается найти указанный файл.

Source Error: 


Line 6:	<!--<add verb="(verbs)" path="(путь к файлу)" type="(полное имя класса,имя сборки)" /> -->
Line 7:	
Line 8:	<add verb="*" path="photo.aspx" type="PictureHandler.PictureHandler,PictureHandler" />
Line 9: 
Line 10: 


Source File: C:\WEBB\FU\web.config	Line: 8


pass: FU
 

Вложения

  • FU.rar
    268 КБ · Просмотры: 199
K

Kreol

так я ж написал как было в примере, или его убить нада эот комент? или что туда прописать?
 
K

Kreol

мжа чего-то не может найти, вроде все прописал
 
K

Kreol

нада правильно
Код:
Inherits="Hello|PictureHandler"
прописать?
 
Мы в соцсетях:

Обучение наступательной кибербезопасности в игровой форме. Начать игру!