java傳送文件
㈠ java中如何實現從客戶端發送文件到伺服器端
伺服器端源碼:x0dx0aimport java.io.BufferedReader;x0dx0aimport java.io.File;x0dx0aimport java.io.FileNotFoundException;x0dx0aimport java.io.FileOutputStream;x0dx0aimport java.io.IOException;x0dx0aimport java.io.InputStream;x0dx0aimport java.io.InputStreamReader;x0dx0aimport java.net.ServerSocket;x0dx0aimport java.net.Socket;x0dx0ax0dx0a/**x0dx0a *x0dx0a * 文件名:ServerReceive.javax0dx0a * 實現功能:作為伺服器接收客戶端發送的文件x0dx0a *x0dx0a * 具體實現過程:x0dx0a * 1、建立SocketServer,等待客戶端的連接x0dx0a * 2、當有客戶端虛鍵毀連接的時候,按照雙方的約定,這時要讀取一行數據x0dx0a * 其中保存客戶端要發送的文件名和文件大小信息x0dx0a * 3、根據文件名在本地創建文件,並建立好流通信x0dx0a * 4、循環接收數據包,將數據包寫入文件x0dx0a * 5、當接收數據的長度等於提前文件發過來的文件長亮伏度,即表示文件接收完畢,關閉文件差備x0dx0a * 6、文件接收工作結束x0dx0ax0dx0apublic class ServerReceive {x0dx0a x0dx0a public static void main(String[] args) {x0dx0a x0dx0a /**與伺服器建立連接的通信句柄*/x0dx0a ServerSocket ss = null;x0dx0a Socket s = null;x0dx0a x0dx0a /**定義用於在接收後在本地創建的文件對象和文件輸出流對象*/x0dx0a File file = null;x0dx0a FileOutputStream fos = null;x0dx0a x0dx0a /**定義輸入流,使用socket的inputStream對數據包進行輸入*/x0dx0a InputStream is = null;x0dx0a x0dx0a /**定義byte數組來作為數據包的存儲數據包*/x0dx0a byte[] buffer = new byte[4096 * 5];x0dx0a x0dx0a /**用來接收文件發送請求的字元串*/x0dx0a String comm = null;x0dx0ax0dx0a/**建立socekt通信,等待伺服器進行連接*/x0dx0a try {x0dx0a ss = new ServerSocket(4004);x0dx0a s = ss.accept();x0dx0a } catch (IOException e) {x0dx0a e.printStackTrace();x0dx0a }x0dx0ax0dx0a/**讀取一行客戶端發送過來的約定信息*/x0dx0a try {x0dx0a InputStreamReader isr = new InputStreamReader(s.getInputStream());x0dx0a BufferedReader br = new BufferedReader(isr);x0dx0a comm = br.readLine();x0dx0a } catch (IOException e) {x0dx0a System.out.println("伺服器與客戶端斷開連接");x0dx0a }x0dx0a x0dx0a /**開始解析客戶端發送過來的請求命令*/x0dx0a int index = comm.indexOf("/#");x0dx0a x0dx0a /**判斷協議是否為發送文件的協議*/x0dx0a String xieyi = comm.substring(0, index);x0dx0a if(!xieyi.equals("111")){x0dx0a System.out.println("伺服器收到的協議碼不正確");x0dx0a return;x0dx0a }x0dx0a x0dx0a /**解析出文件的名字和大小*/x0dx0a comm = comm.substring(index + 2);x0dx0a index = comm.indexOf("/#");x0dx0a String filename = comm.substring(0, index).trim();x0dx0a String filesize = comm.substring(index + 2).trim();x0dx0ax0dx0a/**創建空文件,用來進行接收文件*/x0dx0a file = new File(filename);x0dx0a if(!file.exists()){x0dx0a try {x0dx0a file.createNewFile();x0dx0a } catch (IOException e) {x0dx0a System.out.println("伺服器端創建文件失敗");x0dx0a }x0dx0a }else{x0dx0a /**在此也可以詢問是否覆蓋*/x0dx0a System.out.println("本路徑已存在相同文件,進行覆蓋");x0dx0a }x0dx0a x0dx0a /**【以上就是客戶端代碼中寫到的伺服器的准備部分】*/x0dx0ax0dx0a/**x0dx0a * 伺服器接收文件的關鍵代碼*/x0dx0a try {x0dx0a /**將文件包裝到文件輸出流對象中*/x0dx0a fos = new FileOutputStream(file);x0dx0a long file_size = Long.parseLong(filesize);x0dx0a is = s.getInputStream();x0dx0a /**size為每次接收數據包的長度*/x0dx0a int size = 0;x0dx0a /**count用來記錄已接收到文件的長度*/x0dx0a long count = 0;x0dx0a x0dx0a /**使用while循環接收數據包*/x0dx0a while(count < file_size){x0dx0a /**從輸入流中讀取一個數據包*/x0dx0a size = is.read(buffer);x0dx0a x0dx0a /**將剛剛讀取的數據包寫到本地文件中去*/x0dx0a fos.write(buffer, 0, size);x0dx0a fos.flush();x0dx0a x0dx0a /**將已接收到文件的長度+size*/x0dx0a count += size;x0dx0a System.out.println("伺服器端接收到數據包,大小為" + size);x0dx0a }x0dx0a x0dx0a } catch (FileNotFoundException e) {x0dx0a System.out.println("伺服器寫文件失敗");x0dx0a } catch (IOException e) {x0dx0a System.out.println("伺服器:客戶端斷開連接");x0dx0a }finally{x0dx0a /**x0dx0a * 將打開的文件關閉x0dx0a * 如有需要,也可以在此關閉socket連接x0dx0a * */x0dx0a try {x0dx0a if(fos != null)x0dx0a fos.close();x0dx0a } catch (IOException e) {x0dx0a e.printStackTrace();x0dx0a }//catch (IOException e)x0dx0a }//finallyx0dx0a x0dx0a }//public static void main(String[] args)x0dx0a}//public class ServerReceivex0dx0ax0dx0a客戶端源碼:x0dx0ax0dx0aimport java.io.File;x0dx0aimport java.io.FileInputStream;x0dx0aimport java.io.FileNotFoundException;x0dx0aimport java.io.IOException;x0dx0aimport java.io.OutputStream;x0dx0aimport java.io.PrintStream;x0dx0aimport java.net.Socket;x0dx0ax0dx0a/**x0dx0a *x0dx0a * 文件名:ClientSend.javax0dx0a * 實現功能:作為客戶端向伺服器發送一個文件x0dx0a *x0dx0a * 具體實現過程:x0dx0a * 1、建立與伺服器端的連接,IP:127.0.0.1, port:4004x0dx0a * 2、將文件的名字和大小通過自定義的文件傳輸協議,發送到伺服器x0dx0a * 3、循環讀取本地文件,將文件打包發送到數據輸出流中x0dx0a * 4、關閉文件,結束傳輸x0dx0a *x0dx0a * */x0dx0a x0dx0apublic class ClientSend {x0dx0a x0dx0a public static void main(String[] args) {x0dx0a x0dx0a /**與伺服器建立連接的通信句柄*/x0dx0a Socket s = null;x0dx0a x0dx0a /**定義文件對象,即為要發送的文件x0dx0a * 如果使用絕對路徑,不要忘記使用'/'和'\'的區別x0dx0a * 具體區別,請讀者自行查詢x0dx0a * */x0dx0a File sendfile = new File("API.CHM");x0dx0a /**定義文件輸入流,用來打開、讀取即將要發送的文件*/x0dx0a FileInputStream fis = null;x0dx0a /**定義byte數組來作為數據包的存儲數據包*/x0dx0a byte[] buffer = new byte[4096 * 5];x0dx0a x0dx0a /**定義輸出流,使用socket的outputStream對數據包進行輸出*/x0dx0a OutputStream os = null;x0dx0ax0dx0a/**檢查要發送的文件是否存在*/x0dx0a if(!sendfile.exists()){x0dx0a System.out.println("客戶端:要發送的文件不存在");x0dx0a return;x0dx0a }x0dx0ax0dx0a/**與伺服器建立連接*/x0dx0a try {x0dx0a s = new Socket("127.0.0.1", 4004);x0dx0a }catch (IOException e) {x0dx0a System.out.println("未連接到伺服器");x0dx0a }x0dx0a x0dx0a /**用文件對象初始化fis對象x0dx0a * 以便於可以提取出文件的大小x0dx0a * */x0dx0a try {x0dx0a fis = new FileInputStream(sendfile);x0dx0a } catch (FileNotFoundException e1) {x0dx0a e1.printStackTrace();x0dx0a }x0dx0ax0dx0a/**首先先向伺服器發送關於文件的信息,以便於伺服器進行接收的相關准備工作x0dx0a * 具體的准備工作,請查看伺服器代碼。x0dx0a *x0dx0a * 發送的內容包括:發送文件協議碼(此處為111)/#文件名(帶後綴名)/#文件大小x0dx0a * */x0dx0a try {x0dx0a PrintStream ps = new PrintStream(s.getOutputStream());x0dx0a ps.println("111/#" + sendfile.getName() + "/#" + fis.available());x0dx0a ps.flush();x0dx0a } catch (IOException e) {x0dx0a System.out.println("伺服器連接中斷");x0dx0a }x0dx0ax0dx0a/**x0dx0a * 此處睡眠2s,等待伺服器把相關的工作準備好x0dx0a * 也是為了保證網路的延遲x0dx0a * 讀者可自行選擇添加此代碼x0dx0a * */x0dx0a try {x0dx0a Thread.sleep(2000);x0dx0a } catch (InterruptedException e1) {x0dx0a e1.printStackTrace();x0dx0a }x0dx0ax0dx0a/**之前的准備工作結束之後x0dx0a * 下面就是文件傳輸的關鍵代碼x0dx0a * */x0dx0a try {x0dx0a x0dx0a /**獲取socket的OutputStream,以便向其中寫入數據包*/x0dx0a os = s.getOutputStream();x0dx0a x0dx0a /** size 用來記錄每次讀取文件的大小*/x0dx0a int size = 0;x0dx0a x0dx0a /**使用while循環讀取文件,直到文件讀取結束*/x0dx0a while((size = fis.read(buffer)) != -1){x0dx0a System.out.println("客戶端發送數據包,大小為" + size);x0dx0a /**向輸出流中寫入剛剛讀到的數據包*/x0dx0a os.write(buffer, 0, size);x0dx0a /**刷新一下*/x0dx0a os.flush();x0dx0a }x0dx0a } catch (FileNotFoundException e) {x0dx0a System.out.println("客戶端讀取文件出錯");x0dx0a } catch (IOException e) {x0dx0a System.out.println("客戶端輸出文件出錯");x0dx0a }finally{x0dx0a x0dx0a /**x0dx0a * 將打開的文件關閉x0dx0a * 如有需要,也可以在此關閉socket連接x0dx0a * */x0dx0a try {x0dx0a if(fis != null)x0dx0a fis.close();x0dx0a } catch (IOException e) {x0dx0a System.out.println("客戶端文件關閉出錯");x0dx0a }//catch (IOException e)x0dx0a }//finallyx0dx0a x0dx0a }//public static void main(String[] args)x0dx0a}//public class ClientSend
㈡ 關於用JAVA的SOCKET傳輸文件
點對點傳輸文件
/*
import java.io.*;
import java.net.*;
import java.util.*;
*/
private HttpURLConnection connection;//存儲連接
private int downsize = -1;//下載文件大小,初始值為-1
private int downed = 0;//文加已下載大小,初始值為0
private RandomAccessFile savefile;//記錄下載信息存儲文件
private URL fileurl;//記錄要下載文件的地址
private DataInputStream fileStream;//記錄下載的數據流
try{
/*開始創建下載的存儲文件,並初始化值*/
File tempfileobject = new File("h:\\webwork-2.1.7.zip");
if(!tempfileobject.exists()){
/*文件不存在則建立*/
tempfileobject.createNewFile();
}
savefile = new RandomAccessFile(tempfileobject,"rw");
/*建立連接*/
fileurl = new URL("https://webwork.dev.java.net/files/documents/693/9723/webwork-2.1.7.zip");
connection = (HttpURLConnection)fileurl.openConnection();
connection.setRequestProperty("Range","byte="+this.downed+"-");
this.downsize = connection.getContentLength();
//System.out.println(connection.getContentLength());
new Thread(this).start();
}
catch(Exception e){
System.out.println(e.toString());
System.out.println("構建器錯誤");
System.exit(0);
}
public void run(){
/*開始下載文件,以下測試非斷點續傳,下載的文件存在問題*/
try{
System.out.println("begin!");
Date begintime = new Date();
begintime.setTime(new Date().getTime());
byte[] filebyte;
int onecelen;
//System.out.println(this.connection.getInputStream().getClass().getName());
this.fileStream = new DataInputStream(
new BufferedInputStream(
this.connection.getInputStream()));
System.out.println("size = " + this.downsize);
while(this.downsize != this.downed){
if(this.downsize - this.downed > 262144){//設置為最大256KB的緩存
filebyte = new byte[262144];
onecelen = 262144;
}
else{
filebyte = new byte[this.downsize - this.downed];
onecelen = this.downsize - this.downed;
}
onecelen = this.fileStream.read(filebyte,0,onecelen);
this.savefile.write(filebyte,0,onecelen);
this.downed += onecelen;
System.out.println(this.downed);
}
this.savefile.close();
System.out.println("end!");
System.out.println(begintime.getTime());
System.out.println(new Date().getTime());
System.out.println(begintime.getTime() - new Date().getTime());
}
catch(Exception e){
System.out.println(e.toString());
System.out.println("run()方法有問題!");
}
}
/***
//FileClient.java
import java.io.*;
import java.net.*;
public class FileClient {
public static void main(String[] args) throws Exception {
//使用本地文件系統接受網路數據並存為新文件
File file = new File("d:\\fmd.doc");
file.createNewFile();
RandomAccessFile raf = new RandomAccessFile(file, "rw");
// 通過Socket連接文件伺服器
Socket server = new Socket(InetAddress.getLocalHost(), 3318);
//創建網路接受流接受伺服器文件數據
InputStream netIn = server.getInputStream();
InputStream in = new DataInputStream(new BufferedInputStream(netIn));
//創建緩沖區緩沖網路數據
byte[] buf = new byte[2048];
int num = in.read(buf);
while (num != (-1)) {//是否讀完所有數據
raf.write(buf, 0, num);//將數據寫往文件
raf.skipBytes(num);//順序寫文件位元組
num = in.read(buf);//繼續從網路中讀取文件
}
in.close();
raf.close();
}
}
//FileServer.java
import java.io.*;
import java.util.*;
import java.net.*;
public class FileServer {
public static void main(String[] args) throws Exception {
//創建文件流用來讀取文件中的數據
File file = new File("d:\\系統特點.doc");
FileInputStream fos = new FileInputStream(file);
//創建網路伺服器接受客戶請求
ServerSocket ss = new ServerSocket(8801);
Socket client = ss.accept();
//創建網路輸出流並提供數據包裝器
OutputStream netOut = client.getOutputStream();
OutputStream doc = new DataOutputStream(
new BufferedOutputStream(netOut));
//創建文件讀取緩沖區
byte[] buf = new byte[2048];
int num = fos.read(buf);
while (num != (-1)) {//是否讀完文件
doc.write(buf, 0, num);//把文件數據寫出網路緩沖區
doc.flush();//刷新緩沖區把數據寫往客戶端
num = fos.read(buf);//繼續從文件中讀取數據
}
fos.close();
doc.close();
}
}
*/
㈢ JAVA 傳輸文件
//以前寫的一個文件傳輸的小程序,有客戶端和伺服器端兩部分,伺服器可//以一直運行,客戶端傳輸完一個後退出,當然你也可以根據你的需要改。
//伺服器端可以支持多個客戶端同時上傳,用到了多線程
/**
* 文件傳輸,客戶端
* @aurth anyx
*/
//package per.anyx.ftp;
import java.net.*;
import java.io.*;
public class FtpClient{
public static void main(String[] args){
if(args.length != 3){
System.out.println("Usage: FtpClient host_add host_port src_file");
System.exit(0);
}
File file = new File(args[2]);
if(!file.exists() || !file.isFile()){
System.out.println("File \"" + args[2] + "\" does not exist or is not a normal file.");
System.exit(0);
}
Socket s = null;
FileInputStream in = null;
OutputStream out = null;
try{
s = new Socket(args[0], Integer.parseInt(args[1]));
in = new FileInputStream(file);
out = s.getOutputStream();
byte[] buffer = new byte[1024*8];
int len = -1;
System.out.println("File tansfer statr...");
while((len=in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
System.out.println("File tansfer complete...");
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
System.exit(1);
}finally{
try{
if(in != null) in.close();
if(out != null) out.close();
if(s != null) s.close();
}catch(Exception e){}
}
}
}
/**
* 文件傳輸,伺服器端
* @aurth anyx
*/
//package per.anyx.ftp;
import java.net.*;
import java.io.*;
public class FtpServer{
public static void main(String[] args){
if(args.length != 1){
System.out.println("Usage: FtpServer server_port");
System.exit(0);
}
ServerSocket ss = null;
try{
ss = new ServerSocket(Integer.parseInt(args[0]));
System.out.println("FtpServer start on port ..." + args[0]);
while(true){
Socket s = ss.accept();
new FtpThread(s).start();
System.out.println(s.getInetAddress().getHostAddress() + " connected.");
}
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}finally{
try{
if(ss != null) ss.close();
}catch(Exception e){}
}
}
}
class FtpThread extends Thread{
Socket s;
long fileName = 0;
public FtpThread(Socket s){
this.s = s;
}
public void run(){
FileOutputStream out = null;
InputStream in = null;
File file = null;
do{
file = new File("" + (fileName++));
}while(file.exists());
try{
out = new FileOutputStream(file);
in = s.getInputStream();
byte[] buffer = new byte[1024*8];
int len = -1;
while((len=in.read(buffer)) != -1){
out.write(buffer, 0, len);
}
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}finally{
try{
if(in != null) in.close();
if(out != null) out.close();
if(s != null) s.close();
System.out.println(s.getInetAddress().getHostAddress() + " connect closed..");
}catch(Exception e){}
}
}
}
㈣ java如何實現文件上傳
public static int transFile(InputStream in, OutputStream out, int fileSize) {
int receiveLen = 0;
final int bufSize = 1000;
try {
byte[] buf = new byte[bufSize];
int len = 0;
while(fileSize - receiveLen > bufSize)
{
len = in.read(buf);
out.write(buf, 0, len);
out.flush();
receiveLen += len;
System.out.println(len);
}
while(receiveLen < fileSize)
{
len = in.read(buf, 0, fileSize - receiveLen);
System.out.println(len);
out.write(buf, 0, len);
receiveLen += len;
out.flush();
}
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
return receiveLen;
}
這個方法從InputStream中讀取內容,寫到OutputStream中。
那麼發送文件方,InputStream就是FileInputStream,OutputStream就是Socket.getOutputStream.
接受文件方,InputStream就是Socket.getInputStream,OutputStream就是FileOutputStream。
就OK了。 至於存到資料庫里嘛,Oracle里用Blob。搜索一下,也是一樣的。從Blob能獲取一個輸出流。
㈤ 用Java實現在兩台電腦之間的文件傳輸
使用Socket可以做到,不過直接編程一般都是在區域網內,如果要在不同區域網間通信,需要使用一台有公網IP的伺服器,可以電腦A和電腦B同時連接伺服器,然後A向伺服器傳遞文件,伺服器再將文件轉發電腦B。也可以使用打洞的方式使A、B互聯,此時伺服器的作用是輔助打洞。A、B向伺服器發送信息後socket不要關閉(假設使用10989埠),同時使用Serversocket綁定監聽相同的埠(監聽10989埠)。在java中有參數可以做到,具體方法請自行網路。伺服器獲取到A、B的外網地址和埠,將A的外網地址信息發送給B、將B的外網地址信息發送給A。然後使用A沒有關閉的Socket向B發送一組信息(此時連接會失敗,但是B的路由表上已經記錄了A的信息),發送後A向伺服器發送消息,伺服器告訴B A已經發送消息。然後B使用未關閉的socket向A發送消息,就和A上監聽的ServerSocket取得連接了。之後就可以互相傳遞數據。
㈥ java socket傳送文件
客戶端代碼如下:
importjava.io.DataOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.net.InetSocketAddress;
importjava.net.Socket;
/**
*文件發送客戶端主程序
*@authoradmin_Hzw
*
*/
publicclassBxClient{
/**
*程序main方法
*@paramargs
*@throwsIOException
*/
publicstaticvoidmain(String[]args)throwsIOException{
intlength=0;
doublesumL=0;
byte[]sendBytes=null;
Socketsocket=null;
DataOutputStreamdos=null;
FileInputStreamfis=null;
booleanbool=false;
try{
Filefile=newFile("D:/天啊.zip");//要傳輸的文件路徑
longl=file.length();
socket=newSocket();
socket.connect(newInetSocketAddress("127.0.0.1",48123));
dos=newDataOutputStream(socket.getOutputStream());
fis=newFileInputStream(file);
sendBytes=newbyte[1024];
while((length=fis.read(sendBytes,0,sendBytes.length))>0){
sumL+=length;
System.out.println("已傳輸:"+((sumL/l)*100)+"%");
dos.write(sendBytes,0,length);
dos.flush();
}
//雖然數據類型不同,但JAVA會自動轉換成相同數據類型後在做比較
if(sumL==l){
bool=true;
}
}catch(Exceptione){
System.out.println("客戶端文件傳輸異常");
bool=false;
e.printStackTrace();
}finally{
if(dos!=null)
dos.close();
if(fis!=null)
fis.close();
if(socket!=null)
socket.close();
}
System.out.println(bool?"成功":"失敗");
}
}
服務端代碼如下:
importjava.io.DataInputStream;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.net.ServerSocket;
importjava.net.Socket;
importjava.util.Random;
importcom.boxun.util.GetDate;
/**
*接收文件服務
*@authoradmin_Hzw
*
*/
publicclassBxServerSocket{
/**
*工程main方法
*@paramargs
*/
publicstaticvoidmain(String[]args){
try{
finalServerSocketserver=newServerSocket(48123);
Threadth=newThread(newRunnable(){
publicvoidrun(){
while(true){
try{
System.out.println("開始監聽...");
/*
*如果沒有訪問它會自動等待
*/
Socketsocket=server.accept();
System.out.println("有鏈接");
receiveFile(socket);
}catch(Exceptione){
System.out.println("伺服器異常");
e.printStackTrace();
}
}
}
});
th.run();//啟動線程運行
}catch(Exceptione){
e.printStackTrace();
}
}
publicvoidrun(){
}
/**
*接收文件方法
*@paramsocket
*@throwsIOException
*/
publicstaticvoidreceiveFile(Socketsocket)throwsIOException{
byte[]inputByte=null;
intlength=0;
DataInputStreamdis=null;
FileOutputStreamfos=null;
StringfilePath="D:/temp/"+GetDate.getDate()+"SJ"+newRandom().nextInt(10000)+".zip";
try{
try{
dis=newDataInputStream(socket.getInputStream());
Filef=newFile("D:/temp");
if(!f.exists()){
f.mkdir();
}
/*
*文件存儲位置
*/
fos=newFileOutputStream(newFile(filePath));
inputByte=newbyte[1024];
System.out.println("開始接收數據...");
while((length=dis.read(inputByte,0,inputByte.length))>0){
fos.write(inputByte,0,length);
fos.flush();
}
System.out.println("完成接收:"+filePath);
}finally{
if(fos!=null)
fos.close();
if(dis!=null)
dis.close();
if(socket!=null)
socket.close();
}
}catch(Exceptione){
e.printStackTrace();
}
}
}
㈦ java怎麼把文件傳輸到file
common-fileupload是jakarta項目組開發的一個功能很強大的上傳文件組件
下面先介紹上傳文件到伺服器(多文件上傳):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;
public class upload extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GB2312";
//Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
try {
DiskFileUpload fu = new DiskFileUpload();
// 設置允許用戶上傳文件大小,單位:位元組,這里設為2m
fu.setSizeMax(2*1024*1024);
// 設置最多隻允許在內存中存儲的數據,單位:位元組
fu.setSizeThreshold(4096);
// 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬碟的目錄
fu.setRepositoryPath("c://windows//temp");
//開始讀取上傳信息
List fileItems = fu.parseRequest(request);
// 依次處理每個上傳的拿禪文件
Iterator iter = fileItems.iterator();
//正則匹配,過濾路徑取文件名
String regExp=".+////(.+)$";
//過濾掉的文納敏轎件類型
String[] errorType={".exe",".com",".cgi",".asp"};
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem)iter.next();
//忽略其他不是文件域的所有表單信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals("")) && size==0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result){
for (int temp=0;temp<ERRORTYPE.LENGTH;TEMP++){
if (m.group(1).endsWith(errorType[temp])){
throw new IOException(name+": wrong type");
}
}
try{
//保存上傳的文件到指定的目錄
//在下文中上洞肆傳文件至資料庫時,將對這里改寫
item.write(new File("d://" + m.group(1)));
out.print(name+" "+size+"");
}
catch(Exception e){
out.println(e);
}
}
else
{
throw new IOException("fail to upload");
}
}
}
}
catch (IOException e){
out.println(e);
}
catch (FileUploadException e){
out.println(e);
}
}
}
現在介紹上傳文件到伺服器,下面只寫出相關代碼:
以sql2000為例,表結構如下:
欄位名:name filecode
類型: varchar image
資料庫插入代碼為:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");
代碼如下:
。。。。。。
try{
這段代碼如果不去掉,將一同寫入到伺服器中
//item.write(new File("d://" + m.group(1)));
int byteread=0;
//讀取輸入流,也就是上傳的文件內容
InputStream inStream=item.getInputStream();
pstmt.setString(1,m.group(1));
pstmt.setBinaryStream(2,inStream,(int)size);
pstmt.executeUpdate();
inStream.close();
out.println(name+" "+size+" ");
}
。。。。。。
這樣就實現了上傳文件至資料庫
㈧ java socket如何實現一次傳送多個文件
很簡單,就是把多個文件「變成」一個文件傳送就可以了,每個文件都是一個流,把這些流輸入到一個流中合並流傳輸即可,這個是基本思路。實現差不多以下兩個方法
1、直接流拼接,循環要傳輸的文件列表,多個InputStream,然後輸出到一個OutputStream,這個out就是發送數據的埠,為了接收端能夠識別每個文件從而分割流,需要每個流中結尾添加分隔符。其實這就是HTTP文件上傳的做法。
2、就比較簡單了,職業使用ZIP工具包吧需要傳輸的多文件壓縮成一個文件傳輸,接收端直接解壓縮就完事。
需要注意的是,發送多文件上傳你需要提取計算好總傳輸量位元組大小放在傳輸報文頭部告訴接收端你要發送的數據有多大,不然接收端可能無法完整接收數據。