需要在同一列中一次上传多个图像

时间:2016-10-15 23:20:23

标签: java sql

如上所述我需要将一个图像上传到我的数据库,并且我使用Jfilechooser来选择我的文件 我的代码一次只适用于一个图像,我有一个blob列来保存我的图像

我的SQL查询的代码

try {

        PreparedStatement pst =null;
        ResultSet rst=(ResultSet) pst;

        Connection con=(Connection)    DriverManager.getConnection("jdbc:mysql://localhost/iqari", "root","");
        String sql="UPDATE first SET test = ? WHERE   id  = ?";
        pst=(PreparedStatement) con.prepareStatement(sql);
           int row = masterTable.getSelectedRow();

        Object d =   masterTable.getValueAt(row, 0);
        pst.setBytes(1,person_image);
        pst.setObject(2,d);
        pst.execute();
        JOptionPane.showMessageDialog(mainPanel, "done");
    } catch (Exception e) {


        System.out.println(e.getMessage());
    }

附加我的图片的代码 已编辑

    JFileChooser chooser =new JFileChooser();
    chooser.setMultiSelectionEnabled(true);
    chooser.showOpenDialog(null);

    File[] files = chooser.getSelectedFiles();

    for (File f : files) {
   filename = f.getAbsolutePath();
   try
   {
    File image2 = new File(filename);
    FileInputStream fis = new FileInputStream(image2);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];

    for(int readNum; (readNum = fis.read(buf)) != -1;){
       bos.write(buf, 0, readNum);
     }

     person_image = bos.toByteArray();
    }
     catch (Exception e) {
    JOptionPane.showMessageDialog(null, e);
     }
  }

任何帮助都是有用的人。

1 个答案:

答案 0 :(得分:0)

当您使用.getSelectedFiles()时出现错误的原因是因为它返回的是一个对象数组,而不是一个单个对象。试试这样的事情;

更新了代码,我无法测试这个..

File[] files = chooser.getSelectedFiles();

// instantiates an array of byte arrays of size files.length
byte[][] images = new byte[files.length][];
int numberOfImages = 0;
for (File f : files) {
    filename = f.getAbsolutePath();
    try 
    {
        File image2 = new File(filename);
        FileInputStream fis = new FileInputStream(image2);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];

        for(int readNum; (readNum = fis.read(buf)) != -1;){
           bos.write(buf, 0, readNum);
        }

        person_image = bos.toByteArray();

        // adds the byte array to your array & increases the numberOfImages
        images[numberOfImages++] = person_image;
    } 
    catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
    }
}

在原始SQL代码中更改此部分;

pst = (PreparedStatement) con.prepareStatement(sql);
int row = masterTable.getSelectedRow();

Object d = masterTable.getValueAt(row, 0);
pst.setBytes(1,person_image);
pst.setObject(2,d);
pst.execute();

对此;

for(byte[] imageAsByteArray : images) {
    pst = (PreparedStatement) con.prepareStatement(sql);

    int row = masterTable.getSelectedRow();
    Object d = masterTable.getValueAt(row, 0);

    pst.setBytes(1, imageAsByteArray);
    pst.setObject(2, d);
    pst.execute();
}