从Java中保存MySQL中的图像

Rae*_*hid 3 java mysql swing blob image

我试图从Java swing应用程序中保存MySQL数据库中的图像.我正在使用JFileChsoser来获取图像的路径.然后转换文件,以便它可以保存在BLOB类型的MySQL列中.但是我尝试保存的每个图像都没有正确保存或正确转换.有人能告诉我这里我做错了什么吗?

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);
    }     
}
Run Code Online (Sandbox Code Playgroud)

然后在此之后将其保存到数据库中.

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);
    }  
}
Run Code Online (Sandbox Code Playgroud)

我已经将变量userimage和path声明为全局变量

String path=null;
byte[] userimage=null;
Run Code Online (Sandbox Code Playgroud)

jbx*_*jbx 11

您正在将sql语句中的byte []转换为String,最终会得到不正确的数据.

使用BLOB的正确方法是传递InputStream自身.您可以使用FileInputStream您正在使用的来读取文件.

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() );
Run Code Online (Sandbox Code Playgroud)

当您检索回来,你同样可以得到InputStream来自ResultSet:

InputStream imgStream = resultSet.getBinaryStream(2); 
Run Code Online (Sandbox Code Playgroud)