如何将图像上传到数据库? [英] How to upload an image into database ?

查看:110
本文介绍了如何将图像上传到数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在完成我的项目.那是最后一个角落.但是在白天(8小时)中,我无法迈出一步.请帮我.我会解释清楚.

我想将讲师添加到我的jdbc数据库中.我创建的数据库正在运行,连接没有问题.

讲师将拥有此信息.
*名称
*姓氏
*标题
*İmage(这很重要)

我已经在netbeans中创建了Jpanel.

http://www.imagetoo.com/images/untitlqfq.png [
这是我的数据库视图.

http://www.imagetoo.com/images/untitlkhk.png [

Hello everyone,

I am completing my project. That is last corner. But During the day(8 hours) I couldnt step a step. Please help me. I will explain clearly.

I want to add instructors into my database which is an jdbc. I created database it is working there is no problem with connection.

An instructor will have this information.
*Name
*Surname
*Title
*İmage (This is so important)

I have created Jpanel in netbeans.

http://www.imagetoo.com/images/untitlqfq.png[^]

As you can see in this picture, I cant put a picturebox or whatever it is. I want something like filechooser.

Namely my first problem is this.

Second problem is how to create a table with image. Namely I have used varchar or integers. Based on my research I have seen blob? but I didint understand I am making my image column type as blob but errors.
Last problem is with ''ID'' column. I am taking an error similar ID column can not be assigned to a null value.

And here is my database view.

http://www.imagetoo.com/images/untitlkhk.png[^]

ID > Integer
Image > BLOB
Others >Varchar

If someone helps me I will be very very happy. This is very important for me. I am adding my java code.
SAVE BUTTON CODE

try {
           //1.Kısım Baglantı Saglıyoruz
           this.host = "jdbc:derby://localhost:1527/EMRE";
           this.Name = "emre";
           this.Pass = "2561";
           Connection con = DriverManager.getConnection(host,Name,Pass);

           //2.Kısım Statement Olusturuyorum

           Statement cumle = con.createStatement();


           cumle.executeUpdate("INSERT INTO INSTRUCTOR " + " (INAME, ISURNAME, ITITLE,ID)" + " VALUES ('"+txtInstName.getText()+"','"+txtInstSurname.getText()+"','"+cmbInstTitle.getSelectedItem()+"')");
           JOptionPane.showMessageDialog(null, cmbInstTitle.getSelectedItem()+txtInstName.getText()+ " " + txtInstSurname.getText()+"Has Been Added");
           }
       catch (SQLException ex) {
           JOptionPane.showMessageDialog(null, ex);
       }
   }




桌面应用程序




改进
****************************************************** ************************************
再次问好,

我在网上发现了一些修改过的东西(对我来说真的很困难:))

在保存按钮下




A DESKTOP APPLICATION




IMPROVEMENT
**********************************************************************************
Hello again,

I have found something on the web modified with(really difficult for me :))

Under the save button

try {
          //1.Kısım Baglantı Saglıyoruz
          this.host = "jdbc:derby://localhost:1527/EMRE";
          this.Name = "emre";
          this.Pass = "2561";
          Connection con = DriverManager.getConnection(host,Name,Pass);

          //2.Kısım Statement Olusturuyorum

          Statement cumle = con.createStatement();
          ResultSet rs = null;
          PreparedStatement psmnt = null;
          FileInputStream fis;
          Class.forName("org.apache.derby.jdbc.ClientDriver");
          /* Create a connection by using getConnection() method that takes parameters of string type connection url, user name and password to connect to database. */

          // create a file object for image by specifying full path of image as parameter.
          File image = new File("C:\\Documents and Settings\\temre\\Desktop\\IMAGE\\image.jpg");/* prepareStatement() is used for create statement object that is used for sending sql statements to the specified database. */
          psmnt = con.prepareStatement("insert into INSTRUCTOR(INAME, ISURNAME, IMAGE, ITITLE) "+ "values(DEFAULT)");
          psmnt.setString(1,"EMRE");
          psmnt.setString(2,"emre");
          psmnt.setString(4,"2561");
          fis = new FileInputStream(image);
          psmnt.setBinaryStream(3, (InputStream)fis, (int)(image.length()));/* executeUpdate() method execute specified sql query. Here this query insert data and image from specified address. */
          int s = psmnt.executeUpdate();
          if(s>0)
          {JOptionPane.showMessageDialog(null,"Uploaded successfully !");}
          else
          {JOptionPane.showMessageDialog(null," nooo :( !");}
         }

   catch (Exception ex)  {JOptionPane.showMessageDialog(null,"ERROR !"+ex);}



我遇到了诸如分配的值的数量与指定的或隐含的列的数量不同"之类的错误,这是为什么原因,因为我没有上载图像的框.

请帮我一下.还有一点,我并没有理解在代码内部定义路径吗?为什么需要这样的路径?图像在哪里?



I am taking an error such as "the number of values assigned is not the same as the number of specified or implied columns" This is why because I don''t have a box to upload image.

Please give me hand. And one more, I didint understand defining a path inside code ? Why do I need such a path? Where the images go?

推荐答案

要使用Java(或任何编程语言)上载图像,基本上有两种选择:
-将图片上传为Blob(但您要尝试做的是,但是您需要将图片转换为流->参见示例
此处[^] 进行更深入的讨论)

在我从事的大多数项目中(包括当前的项目),我们都将图片上传到服务器并将路径存储到数据库中.当您要处理与每个请求平均检索10到15张图片的许多用户时,它的速度通常会快得多.与从数据库中检索Blob,将其重新组合为文件并将其返回给用户相比,Web服务器更自然地在路径上传递文件.
尽管您说的是用于学校项目的,但我还是建议您选择将它们存储在服务器上并将其路径保存在数据库中的选项.您可以在此处[^]
To upload an image using Java (or any programming language, for that matter), you basically have two options:
- Upload the picture as a blob (what you''re trying to do, BUT, you need to turn the picture into a stream -> see example here[^] for instance), or:
- Upload the picture to your server, retrieve its path and store that path into your database.

Now, both approaches have advantages and disadvantages (see here[^] for a more in-depth discussion)

In most of the projects I''ve worked on (including my current one) we''ve gone with uploading the pictures to the server and storing the path into the database. It tends to be much, much faster when you''re dealing with lots of users that retrieve an average of 10-15 pictures per request. It also comes more naturally to the webserver to deliver a file at a path, versus you retrieving the blob from the database, recomposing it as a file, and returning it to the user.

Although you said it''s for a school project, I''d advise you to go with the option of storing them on the server and saving their paths in the database. You can find some examples here[^] and here[^]


我将其发布为解决方案,而不是作为评论,因为我认为这是一个较大的解释,而不是评论本身

这行:
I''m posting this as a solution, and not as a comment, because i think it is a larger explanation, and not a comment in itself

This line:
psmnt = con.prepareStatement("insert into INSTRUCTOR(INAME, ISURNAME, IMAGE, ITITLE) "+ "values(DEFAULT)");



PreparedStatement不能这样工作.您需要绑定与插入语句中的列指定的参数数量相同的参数. (即使它们是该列的默认值,也就是DEFAULT关键字的含义).

在您的特定情况下,insert语句将为:



PreparedStatements don''t work that way. You need to bind the same number of parameters as specified by the columns in the insert statement. (Even if they are default values for the column, which is what the DEFAULT key word is).

In your specific case, the insert statement would be:

psmnt = con.prepareStatement("insert into INSTRUCTOR(INAME, ISURNAME, IMAGE, ITITLE) "+ "values(DEFAULT, DEFAULT, DEFAULT, DEFAULT)");


您需要具有与指定的列数相同数量的占位符值(default).这就是为什么它会向您抛出错误.

至于在代码中定义路径,请从这里开始:


You need to have the same number of placeholder values (default) as the number of columns specified. This is why it''s throwing you an error.

As for defining a path inside your code, let''s start here:

File image = new File("C:\\Documents and Settings\\temre\\Desktop\\IMAGE\\image.jpg");


因此,您已经定义了图片所在的路径.但是,如果其他人(例如,我)获得了该应用程序并希望运行该应用程序怎么办?我的计算机中没有该路径,因此将其定义为麻烦的事,而最接近的对应路径(对于我的计算机)将是


So, you have defined a path to where is picture is. BUT, what if someone else (I, for instance) get the application and want to run it? I don''t have that path in my computer and defining it would be a hassle, and the closest corresponding path (for my computer) would be

File image = new File("C:\\Users\\Andrei-PC\\Desktop\\IMAGE\\image.jpg");



定义路径意味着指定默认的文件/文件夹路径,该路径可能适用于大多数计算机,大多数操作系统(无论是Linux,Mac还是Windows).

您可以使用Java中的API来执行此操作,并且可以从系统属性" API开始.例如,您可以发出此命令,并且它可以在Linux和Windows上运行(尚未通过MAC对其进行测试):



Defining a path means specifying a default file/folder path, which is likely to work on most computers, on most operating systems, be it Linux, Mac, or Windows.

You have an API in Java to do that, and you can start with the System Properties API. For instance, you can issue this, and it will work under both Linux and Windows (haven''t tested it with MAC):

System.getProperty("user.home")


在Windows下,它将返回C:\\Users\\Andrei-PC\\,而在Linux下,它将返回/home/Andrei-PC/

现在,有了该路径,您可以从那里开始,并创建一个用于存储文件的文件夹.

祝您好运!


Under Windows, this will return C:\\Users\\Andrei-PC\\, while under Linux it will return /home/Andrei-PC/

Now, having that path, you can start from there, and create a folder where to store your files.

Good luck!


关于fileChooser-您不能直接显示它,这是一种不好的做法.您需要一个浏览"按钮,并且当您的用户按下该按钮时,您将在模式窗口中显示fileChooser.检查以下内容(工作示例,已在我的计算机上测试过).

首先,声明并实例化您的文件选择器:
About the fileChooser - You don''t display it directly, that''s bad practice. You need a "Browse" button, and when your user presses that button, the you display the fileChooser in a modal window. Check below (working example, tested on my computer).

First, declare and instantiate your file chooser:
javax.swing.JFileChooser jFileChooser1 = new javax.swing.JFileChooser();
jFileChooser1.setDialogTitle("Choose file....");




然后,创建一个按钮作为您的浏览按钮(也向其中添加actionListener,以便该按钮知道单击后的操作):




Then, create a button to serve as your browse button (also add actionListener to it, so the button knows what to do when clicked):

javax.swing.JButton jButton1 = new javax.swing.JButton();
jButton1.setText("Browse");
jButton1.addActionListener(new java.awt.event.ActionListener() {
   public void actionPerformed(java.awt.event.ActionEvent evt) {
      jButton1ActionPerformed(evt);
  }
});



最后,定义单击按钮时实际发生的情况:



And finally, define what actually happens when the button is clicked:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    int returnValue = jFileChooser1.showOpenDialog(this);
    jFileChooser1.setVisible(true);
    
    if (returnValue == JFileChooser.APPROVE_OPTION) {
        File file = jFileChooser1.getSelectedFile();
        //Now you have the file, serialize it and upload it to database
    } else {
        //Do what you want to do when user doesn't upload anything
    }
}



另外,我不知道如果您有任何其他问题,我将在多久后做出回应,因为我需要去处理一些问题.
我确实希望其他成员可以过来帮助您.您还可以在Java的Java编程论坛中发布此问题的链接(请勿发布完整问题!).说出您尝试过的内容,您仍然需要帮助,并将其链接到此问题,也许其他人会看看它.



Also, I have no idea how soon I will be able to respond if you have any further problems, as I need to go and take care of some issues.
I do hope another member can come along and help you. You can also post a link to this question in the programming forums, in the Java section (DO NOT POST A FULL QUESTION!). Say what you''ve tried, you still need help, and link it to this question, maybe someone else will take a look at it.

TuranEmre写道:
TuranEmre wrote:

对不起,我忘了.谢谢您的考虑.

Sorry I forgot. Thank you for your consideration.



没问题.如果通过我在这里所做的事情,我帮助某人了解了某件事情的工作原理并可能解决了一个问题,那么一切都很好. CodeProject在需要时为我提供了帮助,所以我只是把它退还了



No problem. If by what I did here I helped someone understand how something works and maybe solve a problem, it''s all ok. CodeProject has helped me when I needed it, so I''m just giving that back


这篇关于如何将图像上传到数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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