将文件直接发送到数据库

时间:2016-07-29 18:35:10

标签: java database outputstream

我希望,在这部分代码中,不是将文件保存到我的计算机,然后再打开,读取它,然后直接发送到数据库。我很感激帮助!

            inputstr_id = new DataInputStream(socket.getInputStream());
            String id_moradia = inputstr_id.readUTF();

            OutputStream out = new FileOutputStream("filename.bmp");

            final byte[] buffer = new byte[2048];
            int read = -1;
            while ((read = inputstr_id.read(buffer)) != -1)
                out.write(buffer, 0, read);

            out.close();

            try {
                File imgfile = new File("filename.bmp");

                  FileInputStream fin = new FileInputStream(imgfile);

                  PreparedStatement pre = con.prepareStatement("UPDATE moradia SET image = ? where id_moradia = ?");
                  pre.setBinaryStream(1,(InputStream)fin,(int)imgfile.length());
                  pre.setString(2,id_moradia);
                  pre.executeUpdate();

            }
            catch (SQLException ex) {
                ex.printStackTrace();}
            System.out.println("A moradia ID: "+ id_moradia + " fez o upload de uma foto com sucesso");

0 个答案:

没有答案