Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


hendra
Upload photo
3 Answer(s)      4 years and 4 months ago
Posted in : Java Beginners


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

Advertisement
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. BufferedImage image=null; JFileChooser chooser = new...()); } } Here I'll get path of the photo in local machine in variable "path" (I
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. BufferedImage image=null; JFileChooser chooser...()); } } Here I'll get path of the photo in local machine in variable "path
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
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
UPLOAD
UPLOAD  how to upload image using html
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
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
iPhone Pick images from Photo Library
iPhone Pick images from Photo Library In this example application we are going to show you how to pick an image from photo library. To choose the photo from the photo library we required to call three different delegates
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 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
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
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
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
image upload
image upload  Hello sir I want to upload image or any other type... be upload in the server and their path should be stored in database either in oracle or my sql. kindly help me.   JSP Upload file and save file path
Imge upload
Imge upload  how to upload image in jsp.I am using Glassfish server..   Here is a code that upload an image on tomcat server and save...;HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>
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
Upload image
Upload image  Hai team, I beginner of Java me now i crated code for to capture image and upload to server. Here i taken a snap but when am going to upload to server it shows decoding failed...How can i clear that bug.please
upload a image
upload a image  sir,how can i upload a image into a specified folder...;&lt;HEAD>&lt;TITLE>Display file upload form to the user&lt...;center">&lt;B>UPLOAD THE FILE&lt;/B>&lt;center>&lt
Jsp Upload
; <p>else { </p> <p>out.println("unsucessfull to upload...;<TITLE>Display file upload form to the user</TITLE></HEAD>...;B>UPLOAD THE FILE</B><center></td> </tr> <tr>
 

 

 

DMCA.com