Upload photo

Upload photo

Morning,

Can you tell me coding how to upload photo.

First, i want to browse the photo from my direktory(*.jpg, *.bmp *.gif), then i click this photo and view in my JFrameForm then i have a button to save this photo to database(MySql).

Second, i want to calling again photo from database(MySql), and view to My JFrameForm.

Thank you very much for your help,

Hendra
View Answers

August 14, 2010 at 10:47 AM

Hi Friend,

Try the following code:

import java.io.*;
import java.sql.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.dnd.*;
import java.awt.datatransfer.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.filechooser.*;

public class Uploader extends JFrame {
public static JFrame frame;
public JList list;
public DefaultListModel model;
public File currentDir;
public DropTarget target;
JButton addButton, removeButton, uploadButton;
public Uploader() {
setSize(600,400);
setResizable(true);
setLocation(100,100);

Action uploadAction = new UploadAction("Upload");
Action browseAction = new BrowseAction("Browse");
JPanel cp = new JPanel();
cp.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
cp.setLayout(new BorderLayout());

setContentPane(cp);
model = new DefaultListModel();
list = new JList(model);
list.getInputMap().put(KeyStroke.getKeyStroke(8,0),"insertAction");
list.setVisibleRowCount(12);
list.setCellRenderer(new ImageCellRenderer());

target = new DropTarget(list,new FileDropTargetListener());
cp.add(new JScrollPane(list),BorderLayout.CENTER);
JPanel buttons = new JPanel();
buttons.setLayout(new FlowLayout(FlowLayout.RIGHT,5,10));
JLabel uploadLabel = new JLabel();
uploadLabel.setLayout(new FlowLayout(FlowLayout.LEFT,5,10));
uploadButton = new JButton(uploadAction);
uploadLabel.add(uploadButton);
addButton = new JButton(browseAction);
buttons.add(addButton);
buttons.add(uploadButton);
cp.add(buttons,BorderLayout.SOUTH);
currentDir = new File(System.getProperty("user.dir"));
}
public int addToListModel(ArrayList filenames) {
int count = 0;
for ( Iterator i = filenames.iterator(); i.hasNext(); ) {
String filename = (String)i.next();
if (!model.contains(filename)) {
model.addElement(filename);
count++;
}
}
return count;
}
public static void main(String [] args) {
frame = new Uploader();
frame.setVisible(true);
}
class BrowseAction extends AbstractAction {
public BrowseAction(String text) { super(text); }

public void actionPerformed(ActionEvent evt) {
JFileChooser chooser = new JFileChooser(currentDir);
chooser.addChoosableFileFilter(new ImageFileFilter());
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
chooser.setMultiSelectionEnabled(true);
chooser.setDragEnabled(true);
chooser.showOpenDialog(frame);
currentDir = chooser.getCurrentDirectory();
File [] files = chooser.getSelectedFiles();
ArrayList filenames = new ArrayList(files.length);
for (int i = 0; i < files.length; i++)
filenames.add(files[i].getName());
addToListModel(filenames);
}
}
class ImageFileFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
if (file.isDirectory()) return false;
String name = file.getName().toLowerCase();
return (name.endsWith(".jpg") || name.endsWith(".png")|| name.endsWith(".gif"));
}
public String getDescription() { return "Images ( *.jpg, *.png,*.gif)"; }
}

August 14, 2010 at 10:48 AM

continue..

class UploadAction extends AbstractAction {
public UploadAction(String text) { super(text); }
public void actionPerformed(ActionEvent evt) {
int selected = list.getSelectedIndex();
Object ob=null;
ob=model.getElementAt(selected);
String fileName=ob.toString();
File file=new File(fileName);
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test";, "root", "root");
PreparedStatement st = con.prepareStatement("insert into file(file,file_data) values(?,?)");
FileInputStream fis = new FileInputStream(file);
st.setString(1,fileName);
st.setBinaryStream(2, (InputStream)fis, (int)(file.length()));
int s = st.executeUpdate();
JOptionPane.showMessageDialog(null,"image is successfully uploaded and inserted.");
}
catch(Exception ex){}
}
}
class ImageCellRenderer extends JLabel implements ListCellRenderer {
public ImageCellRenderer() {
setOpaque(true);
setIconTextGap(12);
}
public Component getListCellRendererComponent(JList list,Object value,int index,boolean isSelected,boolean cellHasFocus){
File f = new File(value.toString());
Border empty = BorderFactory.createEmptyBorder(3,3,3,3);
Border matte = BorderFactory.createMatteBorder(0,0,1,0,Color.white);
setBorder(BorderFactory.createCompoundBorder(matte,empty));
setText(f.getName());
Toolkit toolkit = Toolkit.getDefaultToolkit();
Image icon = toolkit.getImage(f.getPath());
Image scaledIcon = icon.getScaledInstance(40,40,Image.SCALE_FAST);
setIcon(new ImageIcon(scaledIcon));
if (isSelected) {
setBackground(new Color(61,128,223));
setForeground(Color.white);
} else if (index % 2 == 0) {
setBackground(new Color(237,243,254));
setForeground(Color.darkGray);
} else {
setBackground(Color.white);
setForeground(Color.darkGray);
}
return this;
}
}
class FileDropTargetListener extends DropTargetAdapter {
public void dragEnter(DropTargetDragEvent evt) {
frame.requestFocusInWindow();
}
public void drop(DropTargetDropEvent evt) {
try {
Transferable tr = evt.getTransferable();
DataFlavor [] flavors = tr.getTransferDataFlavors();
for ( int i = 0; i < flavors.length; i++ ) {
if ( flavors[i].isFlavorJavaFileListType() ) {
evt.acceptDrop(DnDConstants.ACTION_COPY);
java.util.List list2 = (java.util.List)tr.getTransferData(flavors[i]);
ArrayList filenames = new ArrayList();
for ( int j = 0; j < list2.size(); j++ ) {
String path = list2.get(j).toString();
if ( ((new ImageFileFilter()).accept(new File(path))) ) {
filenames.add(path);
}
}
if (filenames.size() > 0 ) {
int numAdded = addToListModel(filenames);
evt.dropComplete(true);
return;
}
}
JOptionPane.showMessageDialog(frame,"Error","Invalid File Type",JOptionPane.WARNING_MESSAGE);
evt.rejectDrop();
}

} catch (Exception e) {
e.printStackTrace();
evt.rejectDrop();
}
}
}
}

August 14, 2010 at 10:49 AM

continue..

TO retrieve image, try the following code:

import java.sql.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class RetrieveImage {
public static void main(String argv[]) {
JLabel label=new JLabel("Enter image id to search from the database:");
final JTextField text=new JTextField(20);
JButton b=new JButton("Search");
final JLabel l=new JLabel();
JPanel p1=new JPanel();
p1.add(label);
p1.add(text);
p1.add(b);
final JPanel p2=new JPanel();
p2.add(l);
p2.setVisible(false);
JPanel p=new JPanel();
p.add(p1);
p.add(p2);
final JFrame f = new JFrame();
f.setTitle("Display Image From database");
f.add(p);
f.setSize(700,100);
f.setVisible(true);

b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String v=text.getText();
int id=Integer.parseInt(v);
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test";, "root", "root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select image from image where image_id='"+id+"'");
byte[] bytes = null;
if (rs.next()) {
bytes = rs.getBytes(1);
}
rs.close();
stmt.close();
con.close();


Image image = f.getToolkit().createImage(bytes);
l.setIcon(new ImageIcon(image));
p2.setVisible(true);
f.pack();
} catch (Exception ex) {
}

}
});

}
}

Thanks









Related Tutorials/Questions & Answers:
upload photo in xcode
upload photo in xcode  how can i upload a photo in a view in xcode? i am a beginner in xcode please help me
Photo upload, Download
Photo upload, Download  Hi I am using NetBeans IDE for developing... am loading photo. (adsbygoogle = window.adsbygoogle || []).push... I'll get path of the photo in local machine in variable "path" (I dont know whether
Advertisements
PHOTO UPLOAD AND DISPLAY - Struts
PHOTO UPLOAD AND DISPLAY  Hi, This is chandra Mohan. I want some help urgently from your side. My problem is I want to upload the photos and display photos usin Struts technology. Please give me some suggestion to me
Upload Photo to Server
Upload Photo to Server  Hi I am using NetBeans IDE for developing... i am loading photo. (adsbygoogle = window.adsbygoogle || []).push...()); } } Here I'll get path of the photo in local machine in variable "path" . My question
Upload photo - Java Beginners
Upload photo  Morning, Can you tell me coding how to upload photo. First, i want to browse the photo from my direktory(*.jpg, *.bmp *.gif), then i click this photo and view in my JFrameForm then i have a button to save
Photo Upload - JSP-Servlet
Photo Upload  Dear Sir, I want some help you i.e code for image upload and download using Servle/jsp. Thanks&Regards, VijayaBabu.M ...(); %> You have successfully upload the file by the name
how to upload photo - Java Beginners
how to upload photo  dear sir, I has a case like that, first i have jlabel. i want to view data like photo/picture to jlabel. then i have a button...{ public static void main(String[] args){ JFrame frame = new JFrame("Upload Image
photo uploading
photo uploading  i want the code upload the image in oracle database
photo album
photo album  while syncing photos to my photo album in my iphone, the photo albumj ust got crashed i guess. Under photos option i just have the camera roll option now!! What should i do to get the photo album back
photo viwer
photo viwer  i need coding for photo viewer using jsp mysql   Please visit the following link: http://www.roseindia.net/jsp/downloadimage.shtml
Gallery Photo
Gallery Photo  I need to display a photo gallery with the path stored in oracle with the possibility of their supprission (photo management) (with jsf or with jsp)   hi friend, Do not do such task using JSP, Better
photo gallery - Java Beginners
photo gallery  Iam uploading images in the serverusing uploading... it dynamically with out giving the path. please help  Hi friend, For upload image visit to : http://www.roseindia.net/jsp/file_upload/employee_upload
UPLOAD
UPLOAD  how to upload image using html
Adding photo to iPhone simulator
Adding photo to iPhone simulator  Hi, there is no photo in my iPhone simulator.. how can i add one? Please suggest. Thanks
save uiimage to photo library
save uiimage to photo library  How to saved the clicked picture on camera roll in iPhone. I always want to write the file into photo library.   Save UIImage to photo library Creating a camera application in iPhone need
ModuleNotFoundError: No module named 'mera_photo'
ModuleNotFoundError: No module named 'mera_photo'  Hi, My Python... 'mera_photo' How to remove the ModuleNotFoundError: No module named 'mera_photo' error? Thanks   Hi, In your python environment you
ModuleNotFoundError: No module named 'natgeo_photo'
ModuleNotFoundError: No module named 'natgeo_photo'  Hi, My Python... 'natgeo_photo' How to remove the ModuleNotFoundError: No module named 'natgeo_photo' error? Thanks   Hi, In your python
ModuleNotFoundError: No module named 'natgeo_photo'
ModuleNotFoundError: No module named 'natgeo_photo'  Hi, My Python... 'natgeo_photo' How to remove the ModuleNotFoundError: No module named 'natgeo_photo' error? Thanks   Hi, In your python
ModuleNotFoundError: No module named 'photo-org'
ModuleNotFoundError: No module named 'photo-org'  Hi, My Python... 'photo-org' How to remove the ModuleNotFoundError: No module named 'photo... have to install padas library. You can install photo-org python with following
ModuleNotFoundError: No module named 'photo-calendar'
ModuleNotFoundError: No module named 'photo-calendar'  Hi, My... named 'photo-calendar' How to remove the ModuleNotFoundError: No module named 'photo-calendar' error? Thanks   Hi, In your python
ModuleNotFoundError: No module named 'photo-dl'
ModuleNotFoundError: No module named 'photo-dl'  Hi, My Python... 'photo-dl' How to remove the ModuleNotFoundError: No module named 'photo-dl... to install padas library. You can install photo-dl python with following
ModuleNotFoundError: No module named 'photo-gen'
ModuleNotFoundError: No module named 'photo-gen'  Hi, My Python... 'photo-gen' How to remove the ModuleNotFoundError: No module named 'photo... have to install padas library. You can install photo-gen python with following
ModuleNotFoundError: No module named 'photo-grid'
ModuleNotFoundError: No module named 'photo-grid'  Hi, My Python... 'photo-grid' How to remove the ModuleNotFoundError: No module named 'photo-grid' error? Thanks   Hi, In your python environment you
ModuleNotFoundError: No module named 'photo-import'
ModuleNotFoundError: No module named 'photo-import'  Hi, My Python... 'photo-import' How to remove the ModuleNotFoundError: No module named 'photo-import' error? Thanks   Hi, In your python
ModuleNotFoundError: No module named 'photo-org'
ModuleNotFoundError: No module named 'photo-org'  Hi, My Python... 'photo-org' How to remove the ModuleNotFoundError: No module named 'photo... have to install padas library. You can install photo-org python with following
ModuleNotFoundError: No module named 'photo-sorter'
ModuleNotFoundError: No module named 'photo-sorter'  Hi, My Python... 'photo-sorter' How to remove the ModuleNotFoundError: No module named 'photo-sorter' error? Thanks   Hi, In your python
ModuleNotFoundError: No module named 'photo-uploader'
ModuleNotFoundError: No module named 'photo-uploader'  Hi, My... named 'photo-uploader' How to remove the ModuleNotFoundError: No module named 'photo-uploader' error? Thanks   Hi, In your python
ModuleNotFoundError: No module named 'unach-photo'
ModuleNotFoundError: No module named 'unach-photo'  Hi, My Python... 'unach-photo' How to remove the ModuleNotFoundError: No module named 'unach-photo' error? Thanks   Hi, In your python environment
ModuleNotFoundError: No module named 'photo-namer-nautilus'
ModuleNotFoundError: No module named 'photo-namer-nautilus'  Hi...: No module named 'photo-namer-nautilus' How to remove the ModuleNotFoundError: No module named 'photo-namer-nautilus' error? Thanks   Hi
ModuleNotFoundError: No module named 'phyto-photo-utils'
ModuleNotFoundError: No module named 'phyto-photo-utils'  Hi, My... named 'phyto-photo-utils' How to remove the ModuleNotFoundError: No module named 'phyto-photo-utils' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'phyto-photo-utils'
ModuleNotFoundError: No module named 'phyto-photo-utils'  Hi, My... named 'phyto-photo-utils' How to remove the ModuleNotFoundError: No module named 'phyto-photo-utils' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'simple-photo-gallery'
ModuleNotFoundError: No module named 'simple-photo-gallery'  Hi...: No module named 'simple-photo-gallery' How to remove the ModuleNotFoundError: No module named 'simple-photo-gallery' error? Thanks   Hi
ModuleNotFoundError: No module named 'unach-photo-server'
ModuleNotFoundError: No module named 'unach-photo-server'  Hi, My... named 'unach-photo-server' How to remove the ModuleNotFoundError: No module named 'unach-photo-server' error? Thanks   Hi, In your
ModuleNotFoundError: No module named 'wagtail-photo-voter'
ModuleNotFoundError: No module named 'wagtail-photo-voter'  Hi, My... named 'wagtail-photo-voter' How to remove the ModuleNotFoundError: No module named 'wagtail-photo-voter' error? Thanks   Hi
ModuleNotFoundError: No module named 'django-photo-albums'
ModuleNotFoundError: No module named 'django-photo-albums'  Hi, My... named 'django-photo-albums' How to remove the ModuleNotFoundError: No module named 'django-photo-albums' error? Thanks   Hi
View Photo From Db MySql
View Photo From Db MySql  Good Morning Sir, Please help me, I make a small code but i have a error. I want to make viewer photo from database MySql into my project in netbeans. this is my code : try
How to create and use Facebook Shared Photo Albums?
Video Tutorial - How to create and use Facebook Shared Photo Albums? Facebook Shared Photo Albums is the feature added to the Facebook. It is very user... to use Facebook Shared Photo Albums?. We have also included a video tutorial
image upload in webapp/upload folder
image upload in webapp/upload folder  sir i want to store upload image in my project directory WebApp/Upload_image/ pls send the jsp servlet code when i upload the image one error found "system cannot found the specified path
upload video
upload video  hi sir i want to code of upload and download video in mysql database using jsp... and plz give advice which data type is used to store video in table
upload an image
upload an image  Hello, i would like to upload an image to the database. how can i do it? what field type should i set in the database? thanx
upload image
upload image  I want to upload image from user using Jdbc connectivity and servlets and Html pages. I tried code but getting error using multi parts,so please send the code
File Upload
File Upload  when i execute the image upload to mysql database it shows an exception that file path cannot be found
images upload
images upload  I use netbeans IDE 6.8 How i upload any image from any folder to web page
how to upload multiple files in jsp and saving the path in database and the file in folder
how to upload multiple files in jsp and saving the path in database and the file in folder  how to upload multiple files in jsp and saving the path in database and the file in folder I have created a form for the upload of files
ModuleNotFoundError: No module named 'photo-geotag-restful-api-client-library'
ModuleNotFoundError: No module named 'photo-geotag-restful-api-client-library...: ModuleNotFoundError: No module named 'photo-geotag-restful-api-client-library' How to remove the ModuleNotFoundError: No module named 'photo-geotag-restful-api
HTML Upload
HTML Upload  Hi, I want to upload a word / excel document using the html code (web interface)need to get displayed on another webpage. Please let me the coding to display on another webpage using
upload pdf
upload pdf   i want to dispal content of pdf fil and stored into database in human readable form using php . how can i do
upload - JSP-Servlet
Upload jar file  What is the steps to upload Jar file in Java
File Upload in Struts.
File Upload in Struts.  How to do File Upload in Struts
upload image data
upload image data  Hii Upload image dat in csv files

Ads