从Java保存MySQL中的图像 [英] Saving an image in MySQL from Java
问题描述
我正在尝试从Java swing应用程序中保存MySQL数据库中的图像。我正在使用JFileChsoser来获取图像的路径。然后转换文件,以便它可以保存在BLOB类型的MySQL列中。但是我尝试保存的每张图片都没有正确保存或正确转换。有人可以告诉我这里我做错了什么吗?
I am trying to save images in MySQL database from a Java swing application. I am using JFileChsoser to get the path of the image. Then after that converting the file so that it can be saved in the MySQL column which is of BLOB type. But every image I try to save does not save properly or get converted properly. Could someone tell me what I'm doing wrong over here?
private void btn_choosepicActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser picchooser = new JFileChooser();
picchooser.setDialogTitle("Select Image");
picchooser.showOpenDialog(null);
File pic=picchooser.getSelectedFile();
path= pic.getAbsolutePath();
txt_path.setText(path.replace('\\','/'));
try{
File image = new File(path);
FileInputStream fis = new FileInputStream(image);
ByteArrayOutputStream baos= new ByteArrayOutputStream();
byte[] buff = new byte[1024];
for(int readNum; (readNum=fis.read(buff)) !=-1 ; ){
baos.write(buff,0,readNum);
}
userimage=baos.toByteArray();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
然后在此之后我将它保存到数据库中所以。
And then after this Im saving it to the database like so.
private void btn_saveActionPerformed(java.awt.event.ActionEvent evt) {
String user= txt_username.getText();
try{
String sql="insert into imgtst (username,image) values ('"+user+"','"+userimage+"')";
pst=con.prepareStatement(sql);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Saved");
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
我已将变量userimage和path声明为全局变量
and I have declared the variable userimage and path as a global variables
String path=null;
byte[] userimage=null;
推荐答案
您正在将byte []转换为String in你的sql语句,你最终会得到不正确的数据。
You are converting the byte[] to a String in your sql statement, and you will end up with incorrect data.
使用BLOB的正确方法是传递 InputStream
本身。您可以使用 FileInputStream
来读取文件。
The right way to use a BLOB would be to pass the InputStream
itself. You can use the FileInputStream
you are using to read the file.
File image = new File(path);
FileInputStream fis = new FileInputStream ( image );
String sql="insert into imgtst (username,image) values (?, ?)";
pst=con.prepareStatement(sql);
pst.setString(1, user);
pst.setBinaryStream (2, fis, (int) file.length() );
当您将其取回时,您可以同样获得 InputStream
来自 ResultSet
:
When you retrieve it back you can similarly get an InputStream
from the ResultSet
:
InputStream imgStream = resultSet.getBinaryStream(2);
这篇关于从Java保存MySQL中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!