如何从我在ms db上保存的文件路径显示图像(使用OUT图片框) [英] How do I display image(with OUT picturebox) from a file path I saved on ms db

查看:81
本文介绍了如何从我在ms db上保存的文件路径显示图像(使用OUT图片框)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个在线拍卖。我保存了要拍卖的物品到ms访问。我使用fileupload上传图像路径并将其存储为字符串。使用以下代码。

======================== ============================================

i am creating a online auction . i saved items to be auctioned onto ms access . i used fileupload to upload image path and stored it as string .using the following code.
====================================================================

protected void btnAdd_Click(object sender, EventArgs e)
        {
            // Connect.
            useDb.ConnectToDatabase();

            // Check for matches.
            
            string fn = System.IO.Path.GetFileName(PictureUpload.PostedFile.FileName);
            string SaveLocation = Server.MapPath("ITEMS") + "\\" + fn;
            try
            {
                PictureUpload.PostedFile.SaveAs(SaveLocation);
                Response.Write("The file has been uploaded.");
            }
            catch (Exception ex)
            {
                Errorlable3.Text=("Error: " + ex.Message);
                //Note: Exception.Message returns a detailed message that describes the current exception. 
                
            }



             //Insert into access database
            OleDbDataReader dbReader = useDb.ExecuteQuery("INSERT INTO [Items] ([Item Name], [Item Discription], [Selling Price], [Image],[closing] )" +
            " VALUES('" + NameTextBox.Text + "', '" + DiscriptionTextBox.Text + "', '" + PriceTextBox.Text + "', '" + fn +"','"+ Closingbox.Text +"' ) ");
                            
             // Disconnect.
            useDb.DisconnectDatabase();
        }





====================== ==============================================



我尝试了什么:



现在在应该显示的页面上要投标的项目的信息,我可以使用标签显示所有信息,但图像证明是棘手的..代码:

============= ================================================== =====



====================================================================

What I have tried:

now on the page that is supposed to display the info of the item to be bid upon , i can display all the info using labels but image is proving tricky ..here is the code:
====================================================================

protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
        {
            Panel1.Visible = true;

            useDb.ConnectToDatabase();
            
            // Construct a query string using the values from the text boxes.
            string queryString = "SELECT * FROM [Items] WHERE [Item Name] = '"+ DropDownList1.SelectedItem +"'";
            
            // Check for matches.
            dbReader = useDb.ExecuteQuery(queryString);

            while (dbReader.Read())
           
            {
                name.Text = dbReader["Item Name"].ToString();
                discription.Text = dbReader["Item Discription"].ToString();
                selling.Text = dbReader["Selling Price"].ToString();
                closing.Text = dbReader["closing"].ToString();

                //i  need convert image text file path to image 
                Image1.ImageUrl = dbReader["Images"].ToString();
                                
                Image Image1 = dbReader["Images",Server.MapPath("ITEMS") + "\\" + fn];
                
                
 
            }
            
            // Disconnect.
            useDb.DisconnectDatabase();

        }

推荐答案

对于初学者,不要那样做!不要连接字符串以构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。请改用参数化查询。

特别是在一个在线网站上,世界上任何地方的任何人都可以通过输入文本框来做任何他想要的事情或者你的数据...



如果您将图像作为文件,您只需使用HTML图像控件来显示它: HTML图像 [ ^ ]
For starters, don't do it like that! Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead.
Particularly in an online website, where anyone, anywhere in the world, could do anything he wanted with or to your data just by typing in textboxes...

If you've got the image as a file, all you have to do is use an HTML image control to display it: HTML Images[^]


很抱歉,这不是上传和检索图片或文件的方法。这里有许多要点。我将从最重要的开始。



1.您的代码是SQL注入的全开放。这是一个严重的安全威胁。阅读SQL注入此处 [ ^ ]

2.您要将图像上传到单个物理文件夹中。你如何为不同的用户处理同一个文件?如果用户A上传sample.pdf而用户B也上传了sample.pdf,你如何确保这两个文件都被上传,后者不会覆盖前者?

3.该角色的作用是什么?以下行?

Sorry but this is not the way to upload and retrieve images or files. There are a number of points to be noticed here. I will start with the most important.

1. Your code is wide open for SQL injection. This is a serious security threat. Read about SQL injection here[^]
2. You are uploading the images in a single physical folder. How do you handle the same file for different users? If user A uploads sample.pdf and user B also uploads sample.pdf how do you make sure both the files are uploaded and the later does not overwrite the former?
3. What is the role of the following line?
Image Image1 = dbReader["Images",Server.MapPath("ITEMS") + "\\" + fn];

你知道它的作用吗?

你编译了代码吗?以下行的输出是什么?

Do you know what it does?
4. Have you compiled your code? What is the output of the following line?

Server.MapPath("ITEMS")



5.您是否了解Try / Catch的工作原理?即使发生异常,您的代码也会尝试在数据库中插入记录!



一旦你明确了上述几点,我建议你按照这些步骤操作。请注意,以下代码未经过测试。它只是在我脑海里输入。您可能需要进行一些调整。



1.获取目标目录以存储文件。例如,如果您的应用程序中有一个名为Images的目录


5. Do you have an idea how Try/Catch works? Your code try to insert a record in the database even if an exception occur!

Once you are clear with the above points I would suggest to follow these steps. Please note that the below code is not tested. It is just typed here out of my head. You may have to make few adjustments.

1. Get the target directory to store the file. For example if you have a directory in your application named "Images"

string targetFolder = HttpContext.Current.Server.MapPath("~/Images");



在ASP.NET中,〜代字号表示虚拟路径的根(在您的情况下是应用程序根目录)。如果我们不使用它,ASP.NET将无法识别路径是绝对路径还是相对路径。



2.生成上传文件的唯一名称。另外,我建议为每个用户创建一个单独的文件夹来存储文件。


in ASP.NET the "~" tilde indicates the root of a virtual path(In your case the application root). If we do not use it, ASP.NET will not be able to recognize if a path is absolute or relative.

2. Generate a unique name of the file uploaded. Additionally, I would suggest to create a separate folder for each user for storing files.

string randomFileName = Path.GetRandomFileName().Replace(".","");//Because I don't like dot in a file name except for extension 



3.保存文件


3. Save your file

string fileName = randomFileName + PictureUpload.PostedFile.FileName;
PictureUpload.PostedFile.SaveAs(targetFolder + fileName);



4.将文件的URL保存在DB中(仅限fileName)



当您检索记录集时,图像的URL为


4. Save the URL of file in DB(only fileName)

When you retrieve the record set the URL of image as

string imagePath = dbReader["ImageURL"].ToString();//This is the path you store in the DB
Image1.ImageUrl = "~/Images/" + imagePath ;

//根据需要进行调整。



希望它有所帮助。

//Adjust it according to your need.

Hope it helps.


从你指出3.

这就是我上传图片的方式

from you point 3 .
this is how I uploaded the pic
Quote:

//检查匹配。



string fn = System。 IO.Path.GetFileName(PictureUpload.PostedFile.FileName);

string SaveLocation = Server.MapPath(ITEMS)+\\+ fn;

try

{

PictureUpload.PostedFile .SaveAs(SaveLocation);

Response.Write(文件已上传。);

}

catch(Exception ex)

{

Errorlable3.Text =(错误:+ ex.Message);

// Check for matches.

string fn = System.IO.Path.GetFileName(PictureUpload.PostedFile.FileName);
string SaveLocation = Server.MapPath("ITEMS") + "\\" + fn;
try
{
PictureUpload.PostedFile.SaveAs(SaveLocation);
Response.Write("The file has been uploaded.");
}
catch (Exception ex)
{
Errorlable3.Text=("Error: " + ex.Message);


这篇关于如何从我在ms db上保存的文件路径显示图像(使用OUT图片框)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆