Java Socket+mysql Implementation of simple file upload code _java

Source: Internet
Author: User
Tags file upload stub

Recently followed a Web site to learn a small project, because there are classes during the day, so it is written in the evening, today to finish it.

The main project is to implement a file upload, through the client landing, the local files uploaded to the server database (local).

First build two tables as follows:

A File information table

CREATE TABLE ' FileInfo ' ( 
' Fname ' char () not NULL, 
' finfo ' blob not NULL, 
' FId ' int (a) NOT null Auto_increm ENT, 
PRIMARY KEY (' FId ') 

A User Information table

CREATE TABLE ' user ' ( 
' username ' char () not NULL, 
' password ' char (=) NOT null, 
' Useid ' int (ten) NOT null AUT O_increment, 
PRIMARY KEY (' Useid ') 
) Engine=innodb auto_increment=19 DEFAULT Charset=utf8;

User class

Package fileupload; 
Import java.io.Serializable; 
* * User entity class 
* 
/public class user implements 
serializable{private static final long Serialversionuid =-72 79093338433393181L; 
private int useid;//User ID 
private string usename;//user name 
private string usepsd;//user password public users 
() { 
} Public 
User (String usename,string usepsd) { 
super (); 
This.usename = Usename; 
THIS.USEPSD = USEPSD; 
} 
Public User (int useid,string usename,string usepsd) { 
super (); 
This.useid = Useid; 
This.usename = Usename; 
THIS.USEPSD = USEPSD; 
} 
public int Getuseid () {return 
Useid; 
} 
public void Setuseid (int useid) { 
This.useid = Useid; 
} 
Public String Getusename () {return 
usename; 
} 
public void Setusename (String usename) { 
this.usename = usename; 
} 
Public String getusepsd () {return 
usepsd; 
} 
public void setusepsd (String usepsd) { 
this.usepsd = usepsd; 
} 
}

UserService class

Package fileupload; 
/** * User Login and Registration operation category * * Import java.sql.Connection; 
Import Java.sql.DriverManager; 
Import java.sql.PreparedStatement; 
Import Java.sql.ResultSet; 
Import java.sql.SQLException; 
public class UserService {private Connection conn = null; 
Private PreparedStatement ptmt = null; 
Private ResultSet rs = null; User logon public boolean login (user user) {string url = ' jdbc:mysql://localhost:3306/fileupload ';//database connection string String sql = "SELECT * from user where username=?" 
and password=? "; 
try {class.forname ("Org.gjt.mm.mysql.Driver"). newinstance (); 
conn = drivermanager.getconnection (URL, "root", "1995520"); 
ptmt = conn.preparestatement (sql); 
Ptmt.setstring (1, User.getusename ()); 
Ptmt.setstring (2, USER.GETUSEPSD ()); 
rs = Ptmt.executequery (); 
if (Rs.next ()) {return true; 
} catch (Exception e) {e.printstacktrace (); 
Finally {try {rs.close (); 
Ptmt.close (); 
catch (SQLException e) {e.printstacktrace (); 
return false; }//User registration public BooleAn register (user user) {System.out.println ("Hello"); String url = "Jdbc:mysql://localhost:3306/fileupload";//database connection strings String sql = INSERT into user (Username,password) value 
S (?,?) "; 
try {class.forname ("Org.gjt.mm.mysql.Driver"). newinstance (); 
conn = drivermanager.getconnection (URL, "root", "1995520"); 
ptmt = conn.preparestatement (sql); 
Ptmt.setstring (1, User.getusename ()); 
Ptmt.setstring (2, USER.GETUSEPSD ()); 
Ptmt.executeupdate (); 
catch (Exception e) {e.printstacktrace (); 
return false; 
Finally {try {//rs.close (); 
Ptmt.close (); 
catch (SQLException e) {e.printstacktrace (); 
} return true; } 
}

Fileiofo class

Package fileupload; 
Import java.io.Serializable; 
/ 
* * File entity class/Public 
class FileInfo implements serializable{ 
private static final long Serialversionuid = 2554622626228481455L; 
private int fid;//file number 
private String fname;//filename 
private byte[] fcontent;//file content public 
FileInfo () { 
} 
Public FileInfo (String fname,byte[] fcontent) { 
super (); 
This.fname = fname; 
This.fcontent = fcontent; 
} 
Public FileInfo (int fid,string fname,byte[] fcontent) { 
super (); 
This.fid = FID; 
This.fname = fname; 
This.fcontent = fcontent; 
} 
public int Getfid () {return 
fid; 
} 
public void Setfid (int fid) { 
this.fid = FID; 
} 
Public String Getfname () {return 
fname; 
} 
public void Setfname (String fname) { 
this.fname = fname; 
} 
Public byte[] Getfcontent () {return 
fcontent; 
} 
public void Setfcontent (byte[] fcontent) { 
this.fcontent = fcontent; 
} 
}

Fileservice class

Package fileupload; 
/** 
* File Upload Operation class * * 
import java.sql.Connection; 
Import Java.sql.DriverManager; 
Import java.sql.PreparedStatement; 
Import java.sql.SQLException; 
public class Fileservice { 
private Connection conn = null; 
Private PreparedStatement ptmt = null; 
Save the file to the database public 
Boolean save (FileInfo file) { 
String url = "Jdbc:mysql://localhost:3306/fileupload";/ Database connection string string 
sql = "INSERT INTO FileInfo (fname,finfo) value (?,?)"; 
try{ 
class.forname ("Org.gjt.mm.mysql.Driver"). newinstance (); 
conn = drivermanager.getconnection (URL, "root", "1995520"); 
ptmt = conn.preparestatement (sql); 
Ptmt.setstring (1, File.getfname ()); 
Ptmt.setbytes (2,file.getfcontent ()); 
Ptmt.executeupdate (); 
} catch (Exception e) { 
e.printstacktrace (); 
return false; 
} finally{ 
try { 
ptmt.close (); 
} catch (SQLException e) { 
e.printstacktrace (); 
} 
} return true; 
} 

Package fileupload;

 import java.io.IOException; 
Import Java.net.ServerSocket; 
Import Java.net.Socket; * * Start Server class */public class StartServer {@SuppressWarnings ("resource") public static void main (string[] args) {try 
{///1. Create a server-side socket, that is, ServerSocket, specify the bound port and listen for this port serversocket serversocket = new ServerSocket (8888); 
Socket socket = NULL; 
SYSTEM.OUT.PRINTLN ("Server started, waiting for client to connect ..."); 
Loop listening for a connection waiting for a client while (true) {//2. Call the Accept () method to start listening, waiting for the client's connection socket = Serversocket.accept (); 
To create a new thread serverthread Serverthread = the newer serverthread (socket); 
Start thread Serverthread.start (); 
The Catch Block E.printstacktrace () is automatically generated by catch (IOException e) {//TODO); 
The [Java] View plain copy on the code to view the snippet derived from my Code slice package fileupload; 
Import java.io.IOException; /** * Start Client class/public class Startclient {public static void main (string[] args) throws ioexception{socketclient cl 
ient = new Socketclient (); Client.showmainmenu ()///Show main Menu} 

Package fileupload;

Import java.io.IOException; 
Import Java.io.ObjectInputStream; 
Import Java.io.ObjectOutputStream; 
Import Java.net.Socket; 
Import Javax.swing.JOptionPane; 
* * Server-side Multithreading class */public class Serverthread extends Thread {static socket socket = NULL; private static ObjectInputStream Ois = null;//Object Input stream private ObjectOutputStream Oos = null;//Object output stream private UserService US = new UserService ();//user business object Private Fileservice fs = new Fileservice ()//File business object///through construction method, initialize socket public Server 
Thread (socket socket) {serverthread.socket = socket; public void Run () {try {ois = new ObjectInputStream (Socket.getinputstream ());//Receive client message Oos = new OBJECTOUTPUTST Ream (Socket.getoutputstream ());//used to send messages to the client commandtransfer transfer = (commandtransfer) ois.readobject (); Read the instructions that the client sends to the server transfer = Execute (transfer); Executes the instruction operation that the client sends to the server Oos.writeobject (transfer);/Response client} catch (IOException | 
ClassNotFoundException e) {e.printstacktrace (); 
} * * Execute instructions from client to server.Private Commandtransfer Execute (commandtransfer transfer) {String cmd = transfer.getcmd ();//Get the instruction of the current operation (Cmd.equals (" 
Login ")) {//user login username = (user) transfer.getdata (); 
Boolean flag = us.login (user); if (flag) Joptionpane.showmessagedialog (NULL, "Login successful!") 
"); 
Transfer.setflag (flag); if (flag) {//judge whether the landing is successful Transfer.setresult ("Landing success!") 
"); }else{Transfer.setresult ("Username or password is incorrect, please login again!") 
"); 
}}else if (Cmd.equals ("register")) {//user registered username = (user) transfer.getdata (); 
Us.register (user)//Registered users Boolean flag = us.register (user); if (flag) Joptionpane.showmessagedialog (NULL, "registered success!") 
"); 
Transfer.setflag (flag); if (flag) {Transfer.setresult ("registered successfully!") 
"); }else{Transfer.setresult ("Registration failed!") 
"); 
}}else if (Cmd.equals ("UploadFile")) {FileInfo file = (FileInfo) transfer.getdata (); 
Fs.save (file); 
Boolean flag = Fs.save (file); if (flag) Joptionpane.showmessagedialog (null, "Upload success!") 
"); 
Transfer.setflag (flag); if (flag) {Transfer.setresult ("Upload success!") 
"); }else{Transfer.setresult ("Upload failed!") 
"); 
} 
}return transfer; 
}} package FileUpload; 
Import Java.io.BufferedInputStream; 
Import Java.io.FileInputStream; 
Import java.io.FileNotFoundException; 
Import java.io.IOException; 
Import Java.io.ObjectInputStream; 
Import Java.io.ObjectOutputStream; 
Import Java.net.Socket; 
Import java.net.UnknownHostException; 
Import Java.util.Scanner; 
/** * Main Menu class */public class Socketclient {Scanner input = new Scanner (system.in); private static SOCKET socket = null;//Client socket//main Menu public void Showmainmenu () throws IOException {System.out.prin 
TLN ("Welcome to use XX file uploading device"); 
System.out.println ("1. Login to \n2. Register \n3; exit"); 
System.out.println ("****************************"); 
SYSTEM.OUT.PRINTLN ("Please choose:"); 
int choice = Input.nextint ();//Get user's selection socket = new socket ("localhost", 8888); 
Switch (choice) {case 1:showlogin ();//Login break; 
Case 2:showregister ();//register break; 
Case 3:system.out.println ("Welcome to your support for this system"); 
System.exit (0); DEFAULT:SYSTEM.OUT.PRINTLN ("Input is wrong!") 
"); System.exit (0); 
}//user registration private void Showregister () throws IOException {User user = new user (); 
Commandtransfer transfer = new Commandtransfer (); 
int count = 0;//Landing number while (true) {count++; if (Count > 3) {System.out.println ("You have failed to login for 3 consecutive times, the program exits!") 
"); 
System.exit (0); 
System.out.print ("Please enter user name:"); 
User.setusename (Input.next ()); 
System.out.print ("Please enter password:"); 
USER.SETUSEPSD (Input.next ()); 
System.out.print ("Please enter password again:"); 
String Repassword = Input.next (); if (!USER.GETUSEPSD (). Equals (Repassword)) {System.out.println ("Two input passwords are inconsistent!") 
"); 
System.out.println ("**********************"); 
Continue 
} transfer.setcmd ("register"); 
Transfer.setdata (user); try {senddata (transfer);//Send data to server transfer = GetData ();//Get the Data System.out.println (Transfer.getresult ()) returned by the server;//output 
Display results System.out.println ("*****************************"); 
if (Transfer.isflag ()) {break;//registration} catch (Unknownhostexception e) {e.printstacktrace) is no longer repeated if the registration succeeds; catch (IOException e) {E.printstacktracE (); 
The finally {}} showlogin ()///Registered after successful login}//Get Server data public static Commandtransfer GetData () throws IOException { 
TODO auto-generated Method stub objectinputstream ois = null; 
Commandtransfer res = null; 
try {if (socket.isclosed ()) socket = new Socket ("localhost", 8888); 
OIS = new ObjectInputStream (Socket.getinputstream ()); 
res = (Commandtransfer) ois.readobject (); 
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace (); 
finally {if (ois!= null) {try {ois.close (); 
Socket.close (); 
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
}} return res; 
* * * upload file/private void Showuploadfile () throws IOException {System.out.println ("Please enter the absolute path of upload file:"); 
String path = Input.next (); 
FileInfo file = null; 
FileInputStream FIS = null; 
Bufferedinputstream bis = null; String fname = path.suBstring (Path.lastindexof ("/") + 1); 
try {fis = new FileInputStream (path); 
byte[] fcontent = new byte[fis.available ()]; 
bis = new Bufferedinputstream (FIS); 
Bis.read (fcontent); 
File = new FileInfo (fname, fcontent); 
catch (FileNotFoundException e) {e.printstacktrace (); 
finally {bis.close (); 
Fis.close (); 
} commandtransfer transfer = new Commandtransfer (); 
Transfer.setcmd ("UploadFile"); 
Transfer.setdata (file); try {senddata (transfer);//Send data to server transfer = GetData ();//Get the Data System.out.println (Transfer.getresult ()) returned by the server;//output 
Show results} catch (Unknownhostexception e) {e.printstacktrace (); 
catch (IOException e) {e.printstacktrace (); finally {}}///Send data to server public static void SendData (Commandtransfer cmd) throws IOException {//TODO Auto-genera 
Ted Method stub ObjectOutputStream oos = null; 
try {if (socket.isclosed ())//Determine whether the socket is closed, and if it is turned off, open the socket = new socket ("localhost", 8888); 
Oos = new ObjectOutputStream (Socket.getoutputstream ()); Oos.writeoBject (CMD); 
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); 
}//user login private void Showlogin () throws IOException {User user = new user (); 
Commandtransfer transfer = new Commandtransfer (); 
while (true) {System.out.print ("Please enter user name:"); 
User.setusename (Input.next ()); 
System.out.print ("Please enter password:"); 
USER.SETUSEPSD (Input.next ()); 
Transfer.setcmd ("login"); 
Transfer.setdata (user); try {senddata (transfer);//Send data to server transfer = GetData ();//Get the Data System.out.println (Transfer.getresult ()) returned by the server;//output 
Display results System.out.println ("*****************************"); 
if (Transfer.isflag ()) {break;//registration} catch (Unknownhostexception e) {e.printstacktrace) is no longer repeated if the registration succeeds; 
catch (IOException e) {e.printstacktrace (); } finally {}} showuploadfile ()//Login successful file Upload}}

The Operation effect chart is as follows:

The file has been saved to the database, and this project is pretty good for friends who want to practice socket communications and MySQL.

The above is a small series to introduce the Java Socket+mysql implementation of simple file upload, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.