I want to tell me How to save image to the mySQL after the user uploaded.
HINT : using NetBeans GUI Builder
This my code for choose image:
private void btnJFileChooserActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
image2.setIcon(new ImageIcon(ImageIO.read(file)));
} catch (IOException e) {
e.printStackTrace();
}
}
This capture for Setter and Getter:
http://up07.s-oman.net/DVMGa.png
This capture for save button:
http://up07.s-oman.net/P2slSGkcj.png
Did you try saving is as a blob? Here's the link to solution on Stack Overflow: insert BLOB file from Local to DB
Related
Hi there I made a program that consist of jtextfield and couple jbuttons. I want to press a jbutton so that the jtextfields will be save to the computer. Any help will be useful.
I think this will help you..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if (jTxt_text.getText().isEmpty()) {
JOptionPane.showMessageDialog(rootPane, "Field is empty. Fill the filed and try again.");
} else {
//get the text from the jTextField and save it into a varibale.
String inputText = jTxt_text.getText();
//Where to save the file.
String savePath = "C:/test/sample.txt";
//Creating a file object, file is an abstract representation of file and directory pathnames.
File tempFile = new File(savePath);
//Check wther the file is available or not.
if (!tempFile.exists()) {
try {
//Creates the file if it's not exsising.
tempFile.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
try {
//writing process..
FileWriter tempWriter = new FileWriter(tempFile.getAbsoluteFile());
BufferedWriter tempBufferWriter = new BufferedWriter(tempWriter);
tempBufferWriter.write(inputText);
tempBufferWriter.close();
JOptionPane.showMessageDialog(rootPane, "Text file with the written text is successfully saved.");
jTxt_text.setText(null);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Still there's a small problem with this code tempBufferWriter.write(inputText) returns void so.. i don't know how to check wther the process completed successfully from the code itself..
I'm trying to save and load .txt files on my program. I've got methods to read and write the files, but I want the user to be able to choose which name and where the files will be saved using the open/save forms. I've done this so far.
JButton btnLoad = new JButton("Carregar");
btnCarregar.addActionListener(new ActionListener() {
private Component modalToComponent;
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
}
}
});
Right, this actually opens the form, but after that, I don't know where and how use my methods to load the text. I guess, I should use file since it's the selected file, but when I send this file to my methods, it just doesnt work. Any example would be appreciated. Thanks before hand!
You can call a method from the point where the user has selected a file to open (in the if part of the actionPerformed method). So if your reading method is called openFile and accepts a File parameter, you can call 'openFile(file)` as the second statement in your if block:
if (fileChooser.showOpenDialog(modalToComponent) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
openFile(file);
}
A simple example of an openFile method to handle opening a file (in this case by only printing the contents) could look like this:
private void openFile(final File inputFile) {
try (final BufferedReader reader = new BufferedReader(new FileReader(inputFile))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println("line: " + line);
// todo: handle line.
}
} catch (final IOException e) {
e.printStackTrace();
// todo: handle exception.
}
}
I am developing notepad project, would like know how do for save a file.txt, my problem is, I keep the file opening JFileChooser, after selected the local where save intend, but after if save again will open JFileChoose again. I want save. Not save as.
JFileChooser fc = new JFileChooser();
int resp = fc.showSaveDialog(fc);
if (resp == JFileChooser.APPROVE_OPTION) {
PrintStream fileOut = null;
try {
File file = fc.getSelectedFile();
fileOut = new PrintStream(file);
fileOut.print(txtArea.getText());
} catch (FileNotFoundException ex) {
Logger.getLogger(frmNotePad.class.getName()).log(Level.SEVERE, null, ex);
} finally {
fileOut.close();
}
Change you work flow.
Basically, when you first save the file, you need to keep a reference to the File to which you saved to...
public class ... {
private File currentFile;
Now, when you go to save the file, you need to check if the currentFile is null or not. It it is null, you ask the user to select a file, otherwise, you can go ahead and try and save the file...
if (currentFile == null) {
JFileChooser fc = new JFileChooser();
int resp = fc.showSaveDialog(fc);
if (resp == JFileChooser.APPROVE_OPTION) {
currentFile = fc.getSelectedFile();
}
}
// Used to make sure that the user didn't cancel the JFileChooser
if (currentFile != null) {
PrintStream fileOut = null;
try {
fileOut = new PrintStream(file);
fileOut.print(txtArea.getText());
} catch (IOException ex) {
Logger.getLogger(frmNotePad.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fileOut.close();
} catch (IOException exp) {
}
}
If you want a save as an alternate to a save as, have the program store a File object referencing the currently opened file's path so the program is always aware of what it's editing, then just write to the programs file variable
I want to read a file using jFileChooser. jFileChooser will come up after press of a button (say jbutton1ChooseFile) and select the required file. After the selection is complete, another button (say jbutton2) will be used to read the contents of the file which has just been selected by the user. So on clicking on jbutton2, selected file will be read.
I am posting few lines of code so that it would be easy to understand what I mean to say:
private void jButton1ChooseFileChooseFileActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser loadFile= new JFileChooser();
loadFile.setApproveButtonText("Select File");
loadFile.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter f1 = new FileNameExtensionFilter("Text Files", "txt", "text","rtf","doc","docx");
loadFile.setFileFilter(f1);
switch (loadFile.showOpenDialog(EncDecApp.this))
{
case JFileChooser.APPROVE_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "Selection Successfull!",
"Attention!",
JOptionPane.OK_OPTION);
jButton1ChooseFile.setText("File Chosen");
jLabelChooseFile.setText(String.valueOf(loadFile.getSelectedFile()).substring(0,30)+"...");
fileSelect=true;
break;
case JFileChooser.CANCEL_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "No file chosen",
"Attention!",
JOptionPane.OK_OPTION);
loadFile.setSelectedFile(null);
jButton1ChooseFile.setText("Browse..");
jLabelChooseFile.setText("Choose file to encrypt");
break;
case JFileChooser.ERROR_OPTION:
JOptionPane.showMessageDialog(EncDecApp.this, "Error",
"Choosing File",
JOptionPane.OK_OPTION);
loadFile.setSelectedFile(null);
jButton1ChooseFile.setText("Browse..");
jLabelChooseFile.setText("Choose file to encrypt");
}
loadFile.setVisible(true);
}
Upto this it's working perfectly.
Now, the code for jButton2 is as follows:
private void jButton2EncryptEncryptActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//Charset charset=Charset.forName("UTF-8");
int returnVal=loadFile.showOpenDialog(jLabel1);
if(returnVal==loadFile.APPROVE_OPTION)
{
File filePath = loadFile.getSelectedFile();
try{
BufferedReader in = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
jTextArea1.append(line + "\n");
}
in.close();
}
catch(IOException ex)
{
System.err.println("Open plaintext error: "+ex);
}
}
}
Any help will be highly appreciated.
At first glance the problem appears to be that you are using a local variable for the JFileChooser. That is to say, you have the line:
JFileChooser loadFile= new JFileChooser();
In your jButton1ChooseFileChooseFileActionPerformed function, and yet also try to refer to loadFile in your jButton2EncryptEncryptActionPerformed function.
In order to have the loadFile object available to both you need to have said loadFile object be a member of the class to which both functions belong.
Currently I am doing create product. As creating products, you need to insert images. So I came out with an file chooser code using JavaFx. When button is on click, it will call this action event to prompt user to choose image from machine.
public void handle(ActionEvent event){
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilterJPG = new FileChooser.ExtensionFilter("JPG files (*.jpg)", "*.JPG");
FileChooser.ExtensionFilter extFilterPNG = new FileChooser.ExtensionFilter("PNG files (*.png)", "*.PNG");
fileChooser.getExtensionFilters().addAll(extFilterJPG, extFilterPNG);
//Show open file dialog
File file = fileChooser.showOpenDialog(null);
try {
BufferedImage bufferedImage = ImageIO.read(file);
Image image = SwingFXUtils.toFXImage(bufferedImage, null);
myImageView.setImage(image);
} catch (IOException ex) {
Logger.getLogger(CreateProductUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
It works perfectly and I can simply get and display the image chosen by:
myImageView.setImage(image);
Image image = panel.getMyImageView().getImage();
However, when I try to insert this image into database table, I got an error message. Here is my Insert SQL method:
public boolean create() {
boolean success = false;
try {
DBController db = new DBController();
String dbQuery;
db.getConnection();
dbQuery = "INSERT INTO sm_product(productName,productDescription,productPrice,productQuantity,dateOfCreation,productStatus,productImage) VALUES (?,?,?,?,?,?,?)";
PreparedStatement psmnt = db.getConnection().prepareStatement(dbQuery);
psmnt.setString(1, name);
psmnt.setString(2, desc);
psmnt.setDouble(3, price);
psmnt.setInt(4, quantity);
psmnt.setString(5, datestr);
psmnt.setString(6, "Available");
File imageFile = new File("test.png");
RenderedImage renderedImage = SwingFXUtils.fromFXImage(image, null);
ImageIO.write(renderedImage, "png", imageFile); //Change extension appropriately
FileInputStream fis = new FileInputStream(imageFile);
psmnt.setBinaryStream(7, (InputStream) fis, (int) (imageFile.length()));
int s = psmnt.executeUpdate();
//check the value of s and initialize success appropriately
return success;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
My data type for image column is Blob. And it returns me an "Data truncation: Data too long for column 'productImage' at row 1" error message. I even tried to change the data type to varchar(100) and it does not work. I wonder why.
Thanks in advance.
As the exception show out. You image is too long in compare to image column capacity.
You have productImage is BLOB but why you even tried to change to varchar(100) it is so strange.
You must change your image colum data type to BLOB.
For more information, you can see here http://dev.mysql.com/doc/refman/5.0/en/blob.html
Hope this help