fileService類中
//添加文件
public?boolean?addFile(File?f){
try?{
String?sql="insert?into?socket_file(fname,fcontent)?value(?,?)";
conn=DBUtil.getconnection();
PreparedStatement?ps=conn.prepareStatement(sql);
ps.setString(1,?f.getFname());
ps.setBytes(2,?f.getFcontent());
ps.executeUpdate();
return?true;
}?catch?(SQLException?e)?{
e.printStackTrace();
return?false;
}
}
socketClient類中
//文件上傳
public?void?showAddfile(){
System.out.println("請輸入要上傳的文件的覺得路徑(如:e:/imooc/dog.jpg):");
File?file=new?File();
String?path=input.next();
CommandTansfer?transfer=new?CommandTansfer();
FileInputStream?fis=null;
BufferedInputStream?bis=null;
java.io.File?fileInfo=new?java.io.File(path);
if(fileInfo.exists()&&fileInfo.isFile()){
file.setFname(fileInfo.getName());
transfer.setCmd("addFile");
try?{
fis=new?FileInputStream(fileInfo);
byte[]?fcontent=new?byte[fis.available()];
bis=new?BufferedInputStream(fis);
bis.read(fcontent);
file.setFcontent(fcontent);
transfer.setData(file);
//與服務器進行通信
socket=new?Socket("127.0.0.1",?8858);
sendData(transfer);
//接收服務器數據
CommandTansfer?result=getData();
if(result.isFlag()){
System.out.println("********上傳文件成功********");
}else{
System.out.println("********上傳文件失敗********");
}
fis.close();
bis.close();
}catch?(Exception?e)?{
e.printStackTrace();
}
}
}
//向服務器發送數據
private?void?sendData(CommandTansfer?transfer){
OutputStream?out;
try?{
out?=?socket.getOutputStream();
ObjectOutputStream?oos=new?ObjectOutputStream(out);
oos.writeObject(transfer);
oos.flush();
}?catch?(IOException?e)?{
e.printStackTrace();
}
}
//接收服務器的數據
private?CommandTansfer?getData(){
CommandTansfer?result=null;
try?{
ObjectInputStream?ois=new?ObjectInputStream(
socket.getInputStream());
result=(CommandTansfer)ois.readObject();
}?catch?(IOException?e)?{
e.printStackTrace();
}?catch?(ClassNotFoundException?e)?{
e.printStackTrace();
}
return?result;
}
2016-09-01
數據庫中存儲上傳文件內容的類型應為為blob