導航:首頁 > IDC知識 > Java文件傳到伺服器

Java文件傳到伺服器

發布時間:2020-11-17 10:00:04

1、java 實現文件上傳到另一台伺服器,該怎麼解決

上傳本地文件代碼
使用步驟如下:
1.調用AddFile函數添加本地文件,注意路徑需要使用版雙斜框(\\)
2.調用PostFirst函數開始上權傳文件。
JavaScript code?<script type="text/javascript" language="javascript"> var fileMgr = new HttpUploaderMgr(); fileMgr.Load();//載入控制項 window.onload = function() { fileMgr.Init();//初始化控制項 //添加一個本地文件 fileMgr.AddFile("D:\\Soft\\QQ2010.exe"); fileMgr.PostFirst(); };</script>

2、java中如何實現從客戶端發送文件到伺服器端

伺服器端源碼:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
*
* 文件名:ServerReceive.java
* 實現功能:作為伺服器接收客戶端發送的文件
*
* 具體實現過程:
* 1、建立SocketServer,等待客戶端的連接
* 2、當有客戶端連接的時候,按照雙方的約定,這時要讀取一行數據
* 其中保存客戶端要發送的文件名和文件大小信息
* 3、根據文件名在本地創建文件,並建立好流通信
* 4、循環接收數據包,將數據包寫入文件
* 5、當接收數據的長度等於提前文件發過來的文件長度,即表示文件接收完畢,關閉文件
* 6、文件接收工作結束

public class ServerReceive {

public static void main(String[] args) {

/**與伺服器建立連接的通信句柄*/
ServerSocket ss = null;
Socket s = null;

/**定義用於在接收後在本地創建的文件對象和文件輸出流對象*/
File file = null;
FileOutputStream fos = null;

/**定義輸入流,使用socket的inputStream對數據包進行輸入*/
InputStream is = null;

/**定義byte數組來作為數據包的存儲數據包*/
byte[] buffer = new byte[4096 * 5];

/**用來接收文件發送請求的字元串*/
String comm = null;

/**建立socekt通信,等待伺服器進行連接*/
try {
ss = new ServerSocket(4004);
s = ss.accept();
} catch (IOException e) {
e.printStackTrace();
}

/**讀取一行客戶端發送過來的約定信息*/
try {
InputStreamReader isr = new InputStreamReader(s.getInputStream());
BufferedReader br = new BufferedReader(isr);
comm = br.readLine();
} catch (IOException e) {
System.out.println("伺服器與客戶端斷開連接");
}

/**開始解析客戶端發送過來的請求命令*/
int index = comm.indexOf("/#");

/**判斷協議是否為發送文件的協議*/
String xieyi = comm.substring(0, index);
if(!xieyi.equals("111")){
System.out.println("伺服器收到的協議碼不正確");
return;
}

/**解析出文件的名字和大小*/
comm = comm.substring(index + 2);
index = comm.indexOf("/#");
String filename = comm.substring(0, index).trim();
String filesize = comm.substring(index + 2).trim();

/**創建空文件,用來進行接收文件*/
file = new File(filename);
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
System.out.println("伺服器端創建文件失敗");
}
}else{
/**在此也可以詢問是否覆蓋*/
System.out.println("本路徑已存在相同文件,進行覆蓋");
}

/**【以上就是客戶端代碼中寫到的伺服器的准備部分】*/

/**
* 伺服器接收文件的關鍵代碼*/
try {
/**將文件包裝到文件輸出流對象中*/
fos = new FileOutputStream(file);
long file_size = Long.parseLong(filesize);
is = s.getInputStream();
/**size為每次接收數據包的長度*/
int size = 0;
/**count用來記錄已接收到文件的長度*/
long count = 0;

/**使用while循環接收數據包*/
while(count < file_size){
/**從輸入流中讀取一個數據包*/
size = is.read(buffer);

/**將剛剛讀取的數據包寫到本地文件中去*/
fos.write(buffer, 0, size);
fos.flush();

/**將已接收到文件的長度+size*/
count += size;
System.out.println("伺服器端接收到數據包,大小為" + size);
}

} catch (FileNotFoundException e) {
System.out.println("伺服器寫文件失敗");
} catch (IOException e) {
System.out.println("伺服器:客戶端斷開連接");
}finally{
/**
* 將打開的文件關閉
* 如有需要,也可以在此關閉socket連接
* */
try {
if(fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}//catch (IOException e)
}//finally

}//public static void main(String[] args)
}//public class ServerReceive

客戶端源碼:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;

/**
*
* 文件名:ClientSend.java
* 實現功能:作為客戶端向伺服器發送一個文件
*
* 具體實現過程:
* 1、建立與伺服器端的連接,IP:127.0.0.1, port:4004
* 2、將文件的名字和大小通過自定義的文件傳輸協議,發送到伺服器
* 3、循環讀取本地文件,將文件打包發送到數據輸出流中
* 4、關閉文件,結束傳輸
*
* */

public class ClientSend {

public static void main(String[] args) {

/**與伺服器建立連接的通信句柄*/
Socket s = null;

/**定義文件對象,即為要發送的文件
* 如果使用絕對路徑,不要忘記使用'/'和'\'的區別
* 具體區別,請讀者自行查詢
* */
File sendfile = new File("API.CHM");
/**定義文件輸入流,用來打開、讀取即將要發送的文件*/
FileInputStream fis = null;
/**定義byte數組來作為數據包的存儲數據包*/
byte[] buffer = new byte[4096 * 5];

/**定義輸出流,使用socket的outputStream對數據包進行輸出*/
OutputStream os = null;

/**檢查要發送的文件是否存在*/
if(!sendfile.exists()){
System.out.println("客戶端:要發送的文件不存在");
return;
}

/**與伺服器建立連接*/
try {
s = new Socket("127.0.0.1", 4004);
}catch (IOException e) {
System.out.println("未連接到伺服器");
}

/**用文件對象初始化fis對象
* 以便於可以提取出文件的大小
* */
try {
fis = new FileInputStream(sendfile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}

/**首先先向伺服器發送關於文件的信息,以便於伺服器進行接收的相關准備工作
* 具體的准備工作,請查看伺服器代碼。
*
* 發送的內容包括:發送文件協議碼(此處為111)/#文件名(帶後綴名)/#文件大小
* */
try {
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println("111/#" + sendfile.getName() + "/#" + fis.available());
ps.flush();
} catch (IOException e) {
System.out.println("伺服器連接中斷");
}

/**
* 此處睡眠2s,等待伺服器把相關的工作準備好
* 也是為了保證網路的延遲
* 讀者可自行選擇添加此代碼
* */
try {
Thread.sleep(2000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}

/**之前的准備工作結束之後
* 下面就是文件傳輸的關鍵代碼
* */
try {

/**獲取socket的OutputStream,以便向其中寫入數據包*/
os = s.getOutputStream();

/** size 用來記錄每次讀取文件的大小*/
int size = 0;

/**使用while循環讀取文件,直到文件讀取結束*/
while((size = fis.read(buffer)) != -1){
System.out.println("客戶端發送數據包,大小為" + size);
/**向輸出流中寫入剛剛讀到的數據包*/
os.write(buffer, 0, size);
/**刷新一下*/
os.flush();
}
} catch (FileNotFoundException e) {
System.out.println("客戶端讀取文件出錯");
} catch (IOException e) {
System.out.println("客戶端輸出文件出錯");
}finally{

/**
* 將打開的文件關閉
* 如有需要,也可以在此關閉socket連接
* */
try {
if(fis != null)
fis.close();
} catch (IOException e) {
System.out.println("客戶端文件關閉出錯");
}//catch (IOException e)
}//finally

}//public static void main(String[] args)
}//public class ClientSend

3、JAVA中如何將文件上傳到伺服器以供下載

<a href="app的路徑">點擊下載xxx.app</a>

4、java中怎麼把文件上傳到伺服器的指定路徑?

文件從本地到伺服器的功能,其實是為了解決目前瀏覽器不支持獲取本地文件全路徑。不得已而想到上傳到伺服器的固定目錄,從而方便項目獲取文件,進而使程序支持EXCEL批量導入數據。

java中文件上傳到伺服器的指定路徑的代碼:

在前台界面中輸入:

<form method="post" enctype="multipart/form-data"  action="../manage/excelImport.do">

請選文件:<input type="file"  name="excelFile">

<input type="submit" value="導入" onclick="return impExcel();"/>

</form>

action中獲取前台傳來數據並保存

/**

* excel 導入文件

* @return

* @throws IOException

*/

@RequestMapping("/usermanager/excelImport.do")

public String excelImport(

String filePath,

MultipartFile  excelFile,HttpServletRequest request) throws IOException{

log.info("<<<<<<action:{} Method:{} start>>>>>>","usermanager","excelImport" );

if (excelFile != null){

String filename=excelFile.getOriginalFilename();

String a=request.getRealPath("u/cms/www/201509");

SaveFileFromInputStream(excelFile.getInputStream(),request.getRealPath("u/cms/www/201509"),filename);//保存到伺服器的路徑

}

log.info("<<<<<<action:{} Method:{} end>>>>>>","usermanager","excelImport" );

return "";

}

/**

* 將MultipartFile轉化為file並保存到伺服器上的某地

*/

public void SaveFileFromInputStream(InputStream stream,String path,String savefile) throws IOException

{  

FileOutputStream fs=new FileOutputStream( path + "/"+ savefile);

System.out.println("------------"+path + "/"+ savefile);

byte[] buffer =new byte[1024*1024];

int bytesum = 0;

int byteread = 0;

while ((byteread=stream.read(buffer))!=-1)

{

bytesum+=byteread;

fs.write(buffer,0,byteread);

fs.flush();

}

fs.close();

stream.close();

}

5、JAVA如何把本地文件上傳到伺服器。

這個你就要參考,java上傳文件的相關資料了。
告訴你有現成的代碼,你可以找寫拷貝過去直接使用。

6、JAVA 把文件傳到伺服器.......

文件上傳到A以後 放到伺服器上面 然後他就有一個絕對的訪問路徑 也就是對應一個絕對的url 這樣就好辦了
Java提供了對URL訪問和大量的流操作的的API,可以很容易的完成對網路上資源的存取,下面的代碼段就完成了對一個網站的資源進行訪問:

......
destUrl="http://www.yourweb.com/java/Afile.zip";
//假設你把文件放到webroot底下的java文件裡面
url = new URL(destUrl);
httpUrl = (HttpURLConnection) url.openConnection();
//連接指定的網路資源
httpUrl.connect();
//獲取網路輸入流
bis = new BufferedInputStream(httpUrl.getInputStream());
......

得到流後下面你自己想怎麼操作就怎麼操作了

對於怎麼得到資源的連接地址這個方法很多 你可以專門提供一個Servlet 獲取到輸出的流後 Response.write轉門提供伺服器已上傳的文件 文件名可以一天位單位返回
客戶端用與上面同樣的方法得到文件名後 拆分 然後再繼續循環調用上面的方法 下載文件就ok了

呵呵 希望可以幫助到你

7、java如何解壓頁面上傳到伺服器的zip文件

這個轉換肯定是會出錯的,struts 的formFile跟zipFile沒有直接關系,怎麼能這么強制轉化呢?專
建議
1. 把文件保存到一個屬臨時目錄(保存為zip文件)
2. 讀取這個文件
3. 抽取想要的文件
4. 把臨時文件刪除

8、java後台文件上傳到資源伺服器上

package com.letv.dir.cloud.util;import com.letv.dir.cloud.controller.DirectorWatermarkController;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import java.io.*;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;/** * Created by xijunge on 2016/11/24 0024. */public class HttpRequesterFile { private static final Logger log = LoggerFactory.getLogger(HttpRequesterFile.class); private static final String TAG = "uploadFile"; private static final int TIME_OUT = 100 * 1000; // 超時時間 private static final String CHARSET = "utf-8"; // 設置編碼 /** * 上傳文件到伺服器 * * @param file * 需要上傳的文件 * @param RequestURL * 文件伺服器的rul * @return 返回響應的內容 * */ public static String uploadFile(File file, String RequestURL) throws IOException {
String result = null;
String BOUNDARY = "letv"; // 邊界標識 隨機生成 String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 內容類型 try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允許輸入流 conn.setDoOutput(true); // 允許輸出流 conn.setUseCaches(false); // 不允許使用緩存 conn.setRequestMethod("POST"); // 請求方式 conn.setRequestProperty("Charset", CHARSET); // 設置編碼 conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

9、java怎麼實現上傳文件到伺服器

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+" ");

}

。。。。。。

這樣就實現了上傳文件至資料庫

10、javaweb 怎麼樣將本地文件傳輸到遠程伺服器

可以通過JDK自帶的API實現,如下代碼:
package com.cloudpower.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

/**
* Java自帶的API對FTP的操作
* @Title:Ftp.java
*/
public class Ftp {
/**
* 本地文件名
*/
private String localfilename;
/**
* 遠程文件名
*/
private String remotefilename;
/**
* FTP客戶端
*/
private FtpClient ftpClient;

/**
* 伺服器連接
* @param ip 伺服器IP
* @param port 伺服器埠
* @param user 用戶名
* @param password 密碼
* @param path 伺服器路徑
* @date 2012-7-11
*/
public void connectServer(String ip, int port, String user,
String password, String path) {
try {
/* ******連接伺服器的兩種方法*******/
//第一種方法
// ftpClient = new FtpClient();
// ftpClient.openServer(ip, port);
//第二種方法
ftpClient = new FtpClient(ip);

ftpClient.login(user, password);
// 設置成2進制傳輸
ftpClient.binary();
System.out.println("login success!");
if (path.length() != 0){
//把遠程系統上的目錄切換到參數path所指定的目錄
ftpClient.cd(path);
}
ftpClient.binary();
} catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
public void closeConnect() {
try {
ftpClient.closeServer();
System.out.println("disconnect success");
} catch (IOException ex) {
System.out.println("not disconnect");
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
public void upload(String localFile, String remoteFile) {
this.localfilename = localFile;
this.remotefilename = remoteFile;
TelnetOutputStream os = null;
FileInputStream is = null;
try {
//將遠程文件加入輸出流中
os = ftpClient.put(this.remotefilename);
//獲取本地文件的輸入流
File file_in = new File(this.localfilename);
is = new FileInputStream(file_in);
//創建一個緩沖區
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
System.out.println("upload success");
} catch (IOException ex) {
System.out.println("not upload");
ex.printStackTrace();
throw new RuntimeException(ex);
} finally{
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void download(String remoteFile, String localFile) {
TelnetInputStream is = null;
FileOutputStream os = null;
try {
//獲取遠程機器上的文件filename,藉助TelnetInputStream把該文件傳送到本地。
is = ftpClient.get(remoteFile);
File file_in = new File(localFile);
os = new FileOutputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
System.out.println("download success");
} catch (IOException ex) {
System.out.println("not download");
ex.printStackTrace();
throw new RuntimeException(ex);
} finally{
try {
if(is != null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os != null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public static void main(String agrs[]) {

String filepath[] = { "/temp/aa.txt", "/temp/regist.log"};
String localfilepath[] = { "C:\\tmp\\1.txt","C:\\tmp\\2.log"};

Ftp fu = new Ftp();
/*
* 使用默認的埠號、用戶名、密碼以及根目錄連接FTP伺服器
*/
fu.connectServer("127.0.0.1", 22, "anonymous", "IEUser@", "/temp");

//下載
for (int i = 0; i < filepath.length; i++) {
fu.download(filepath[i], localfilepath[i]);
}

String localfile = "E:\\號碼.txt";
String remotefile = "/temp/哈哈.txt";
//上傳
fu.upload(localfile, remotefile);
fu.closeConnect();
}
}

與Java文件傳到伺服器相關的知識