将图像上传到localhost mysql

时间:2018-06-22 22:04:06

标签: java mysql javafx jdbc

我想将图像文件保存到本地MySQL数据库。 personalDetails表中的“已创建图像(blob)”列。

如屏幕截图所示,当我单击“保存”按钮时,每个值都正确地存储在数据库中,但是我无法对图像进行处理。我尝试了很多方法,但无法使其正常工作。这是所有页面代码。数据和MySQL之间还有其他连接代码。我该怎么做?

Screenshot

package sample.controllerPart;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;import javafx.fxml.Initializable;import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.StageStyle;import sample.helpers.plus;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.io.IOException;
import java.sql.*;
import java.util.ResourceBundle;

public class developersController implements Initializable {
    FileInputStream fis;
    @FXML private TextField nameField; @FXML private TextField familyNameField; @FXML private DatePicker  dateOfBirthField; @FXML private TextField genderField; @FXML private TextField nationField; @FXML private TextField civilStatusField; @FXML private TextField profileCodeField;
    @FXML private TextField workProgramming; @FXML private TextField workWebDesign; @FXML private TextField workOperatingSys; @FXML private TextField workDatabaseMng; @FXML private TextField workGraphicDesign; @FXML private TextField workPcHardware; @FXML private TextField workOther;
    @FXML private TextField oPosition; @FXML private TextField oPhone; @FXML private TextField oMail; @FXML private TextField oGithub; @FXML private DatePicker  oAdmissionDate; @FXML private TextField oLocation; @FXML private TextField oSalary;
    @FXML  private Text personalText; @FXML  private Text personalText2; @FXML private Text personalText3; @FXML private Text personalText4;  @FXML  private Text personalText5;  @FXML  private Text personalText6;   @FXML   private Text personalText7;
    @FXML private Text workText; @FXML private Text workText2; @FXML private Text workText3; @FXML private Text workText4; @FXML private Text workText5; @FXML private Text workText6; @FXML private Text workText7; @FXML private Text otherDetailText; @FXML private Text otherDetailText2; @FXML private Text otherDetailText3; @FXML private Text otherDetailText4; @FXML private Text otherDetailText5; @FXML private Text otherDetailText6; @FXML private Text otherDetailText7;
    @FXML private Text listNFNText; @FXML private Text listNFNTextx; @FXML private Text listPText; @FXML private Text listPTextx; @FXML private Text listNFNText2; @FXML private Text listNFNTextx2; @FXML private Text listPText2; @FXML private Text listPTextx2; @FXML private Text listNFNText3; @FXML private Text listNFNTextx3; @FXML private Text listPText3; @FXML private Text listPTextx3; @FXML private Text listNFNText4; @FXML private Text listNFNTextx4; @FXML private Text listPText4; @FXML private Text listPTextx4; @FXML private Text listNFNText5; @FXML private Text listNFNTextx5; @FXML private Text listPText5; @FXML private Text listPTextx5; @FXML private Text listNFNText6; @FXML private Text listNFNTextx6; @FXML private Text listPText6; @FXML private Text listPTextx6;
    @FXML
    private ImageView imageData;
    @FXML
    private ImageView imageDatabase;
    @FXML
    private Button uPicture;



    @FXML
    private void uploadPhoto(ActionEvent event) {
        FileChooser fc = new FileChooser();
        fc.setTitle("Open File");
        File selectedFile = fc.showOpenDialog(null);
        String url = selectedFile.toURI().toString();
        if(selectedFile != null) {

            imageData.setImage(new Image(url));
            imageData.maxWidth(119);
            imageData.maxHeight(169);
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }
    @FXML private void add_developers(javafx.scene.input.MouseEvent mouseEvent) throws IOException {

        Dialog parentDialog = new Dialog();
        Parent root = plus.loadFXML("add_developers");
        parentDialog.getDialogPane().setContent(root);
        root.setStyle("-fx-background-color:transparent");
        parentDialog.initStyle(StageStyle.TRANSPARENT);
        parentDialog.show(); }

    int v = 0;
    @FXML private void savePersonal (MouseEvent mouseEvent) throws SQLException {
        ResultSet rs = null;
        PreparedStatement pst = null;
        DatePicker pw;
        sample.controllerPart.ConnectionClass connectionClass = new sample.controllerPart.ConnectionClass();
        Connection connection = connectionClass.getConnection();

        String sql = "INSERT INTO PERSONALDETAILS" +
                "(Name, familyName, dateOfBirth,gender, nation, civilStatus, profileCode, programmingExp, webDesignExp, operatingSysExp, databaseMngExp, graphicDesignExp, pcHardwareExp, otherExp, position, phone, mail, github, admissionDate, location, salary) " +
                "VALUES('"+nameField.getText()+"', '"+familyNameField.getText()+"', '"+dateOfBirthField.getValue()+"'," + " '"+genderField.getText()+"', '"+nationField.getText()+"', '"+civilStatusField.getText()+"', '"+profileCodeField.getText()+"', '" +workProgramming.getText()+"','"+workWebDesign.getText()+"','"+workOperatingSys.getText()+"','"+workDatabaseMng.getText()+"', '"+workGraphicDesign.getText()+"', '"+workPcHardware.getText()+"','"+workOther.getText()+"', '" +oPosition.getText()+"','"+oPhone.getText()+"','"+oMail.getText()+"','"+oGithub.getText()+"','"+oAdmissionDate.getValue()+"','"+oLocation.getText()+"','"+oSalary.getText()+"')";
        Statement statement = connection.createStatement();
        statement.executeUpdate(sql);

        String query = "SELECT * FROM PERSONALDETAILS where name = ?";
        pst = connection.prepareStatement(query);
        pst.setString(1, (String) nameField.getText());

        rs = pst.executeQuery();
        int x = 0;
        while(rs.next()){
            personalText.setText(rs.getString("name"));
            personalText2.setText(rs.getString("familyName"));
            personalText3.setText(rs.getString("dateOfBirth"));
            personalText4.setText(rs.getString("gender"));
            personalText5.setText(rs.getString("nation"));
            personalText6.setText(rs.getString("civilStatus"));
            personalText7.setText(rs.getString("profileCode"));

            workText.setText(rs.getString("programmingExp"));
            workText2.setText(rs.getString("webDesignExp"));
            workText3.setText(rs.getString("operatingSysExp"));
            workText4.setText(rs.getString("databaseMngExp"));
            workText5.setText(rs.getString("graphicDesignExp"));
            workText6.setText(rs.getString("pcHardwareExp"));
            workText7.setText(rs.getString("otherExp"));

            otherDetailText.setText(rs.getString("position"));
            otherDetailText2.setText(rs.getString("phone"));
            otherDetailText3.setText(rs.getString("mail"));
            otherDetailText4.setText(rs.getString("github"));
            otherDetailText5.setText(rs.getString("admissionDate"));
            otherDetailText6.setText(rs.getString("location"));
            otherDetailText7.setText(rs.getString("salary"));
        }
        pst.close();
        rs.close();
        if (v == 0) {
            listNFNText.setText(personalText.getText());
            listNFNTextx.setText(personalText2.getText());
            listPText.setText(otherDetailText.getText());
            listPTextx.setText(personalText7.getText());
            v = 1;
        }
        else if (v == 1) {
            listNFNText2.setText(personalText.getText());
            listNFNTextx2.setText(personalText2.getText());
            listPText2.setText(otherDetailText.getText());
            listPTextx2.setText(personalText7.getText());
            v = 2;
        }
        else if (v == 2) {
            listNFNText3.setText(personalText.getText());
            listNFNTextx3.setText(personalText2.getText());
            listPText3.setText(otherDetailText.getText());
            listPTextx3.setText(personalText7.getText());
            v = 3;
        }
        else if (v == 3) {
            listNFNText4.setText(personalText.getText());
            listNFNTextx4.setText(personalText2.getText());
            listPText4.setText(otherDetailText.getText());
            listPTextx4.setText(personalText7.getText());
            v = 4;
        }
        else if (v == 4) {
            listNFNText5.setText(personalText.getText());
            listNFNTextx5.setText(personalText2.getText());
            listPText5.setText(otherDetailText.getText());
            listPTextx5.setText(personalText7.getText());
            v = 5;
        }
        else if (v == 5) {
            listNFNText6.setText(personalText.getText());
            listNFNTextx6.setText(personalText2.getText());
            listPText6.setText(otherDetailText.getText());
            listPTextx6.setText(personalText7.getText());
            v = 0;
        }

}}

1 个答案:

答案 0 :(得分:0)

使用SwingFXUtils转换为BufferedImage,然后使用ImageIO将数据保存到ByteArrayOutputStream。从与Blob一起使用的结果byte[]数组创建的PreparedStatement,将数据插入数据库。

private Connection conn;

@Override
public void init() throws Exception {
    MysqlDataSource dataSource = new MysqlDataSource();
    dataSource.setUser(USERNAME);
    dataSource.setPassword(PASSWORD);
    dataSource.setServerName(SERVER);
    dataSource.setDatabaseName(DATABASE_NAME);
    conn = dataSource.getConnection();

    try (Statement stm = conn.createStatement()) {
        // initialize table
        stm.execute("CREATE TABLE IF NOT EXISTS images ("
                + "id INT AUTO_INCREMENT PRIMARY KEY, "
                + "image LONGBLOB)");
    }
}

@Override
public void stop() throws Exception {
    if (conn != null) {
        conn.close();
    }
}

@Override
public void start(Stage primaryStage) {
    ImageView imageView = new ImageView();
    Button open = new Button("open");
    Button submit = new Button("submit");
    Button retrieve = new Button("retrieve");
    TextField tf = new TextField();
    TextFormatter<Integer> formatter = new TextFormatter<>(new IntegerStringConverter());
    tf.setTextFormatter(formatter);

    open.setOnAction(evt -> {
        FileChooser chooser = new FileChooser();
        File file = chooser.showOpenDialog(primaryStage);
        if (file != null) {
            Image image = new Image(file.toURI().toString());
            imageView.setImage(image);
        }
    });

    submit.setOnAction(evt -> {
        Image image = imageView.getImage();
        Integer id = formatter.getValue();
        if (image != null && id != null) {
            try (PreparedStatement stm = conn.prepareStatement("INSERT INTO images (id, image) VALUES (?, ?) ON DUPLICATE KEY UPDATE image = ?")) {
                // write data to in-memory stream
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                BufferedImage bi = SwingFXUtils.fromFXImage(image, null);
                ImageIO.write(bi, "jpg", bos);

                Blob blob = new SerialBlob(bos.toByteArray());
                stm.setInt(1, id);
                stm.setBlob(2, blob);
                stm.setBlob(3, blob);
                stm.executeUpdate();
            } catch (IOException | SQLException ex) {
                ex.printStackTrace();
            }
        }
    });

    retrieve.setOnAction(evt -> {
        Integer id = formatter.getValue();
        if (id != null) {
            imageView.setImage(null);
            try (PreparedStatement stm = conn.prepareStatement("SELECT image FROM images WHERE id = ?")) {
                stm.setInt(1, id);
                ResultSet rs = stm.executeQuery();
                if (rs.next()) {
                    // read image data from db
                    Blob data = rs.getBlob(1);
                    imageView.setImage(new Image(data.getBinaryStream()));
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
    });
    VBox root = new VBox(tf, new HBox(open, submit, retrieve), imageView);

    Scene scene = new Scene(root, 500, 500);

    primaryStage.setScene(scene);
    primaryStage.show();
}