當前位置:首頁 » 文件管理 » ftp批量上傳java

ftp批量上傳java

發布時間: 2022-10-29 04:06:45

A. java中用多線程可以提高 ftp批量上傳的速度嗎

可以把文件打包上傳,再在線解壓

B. 救火,如何用JAVA實現FTP多文件上傳

新建一個web工程,用來測試上傳功能。搭建好從前台訪問後台的整個框架,並測試是否能接受參數。從apache官網上下載jar包,這里我們需要的jar包共三個,從官網或者其他途徑都可以下載得到。編寫上傳的工具類。工具類主要是涉及兩個方法,首先是連接伺服器的方法。和我們平常常用的連接資料庫等的方法類似,需要有伺服器名,用戶名和密碼。第二個主要的方法就是上傳的方法,上傳的方法接受一個文件,這里需要注意的,需要去判斷傳入的是一個文件還是一個文件夾,如果是文件夾,需要循環進行文件上傳處理。寫方法調用工具類里的方法,並測試上傳功能。這里需要注意的是連接伺服器的埠號,20表示連接伺服器,21表示有上傳操作。

C. java ftp上傳5G以上大文件,怎麼做

java上傳可以使用common-fileupload上傳組件的。common-fileupload是jakarta項目組開發的一個功能很強大的上傳文件組件下面先介紹上傳文件到伺服器(多文件上傳):import javax.servlet.*; import javax.servlet.http.*; import java.io.*;

D. java實現多文件上傳

即使再多文件也是通過的單個文件逐次上傳的(zip等壓縮包實際上是一個文件)。實現思路就是將多個文件循環進行上傳,上傳方法舉例:
/**
* 上傳文件
*
* @param fileName
* @param plainFilePath 文件路徑路徑
* @param filepath
* @return
* @throws Exception
*/
public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FTPClient ftpClient = new FTPClient();
String bl = "false";
try {
fis = new FileInputStream(plainFilePath);
bos = new ByteArrayOutputStream(fis.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = fis.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
Log.info("加密上傳文件開始");
Log.info("連接遠程上傳伺服器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
FTPFile[] fs;
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(filepath)) {
bl="true";
ftpClient.changeWorkingDirectory("/"+filepath+"");
}
}
Log.info("檢查文件路徑是否存在:/"+filepath);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon( "查詢文件路徑不存在:"+"/"+filepath);
return bl;
}
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
// 設置文件類型(二進制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(fileName, fis);
Log.info("上傳文件成功:"+fileName+"。文件保存路徑:"+"/"+filepath+"/");
return bl;
} catch (Exception e) {
throw e;
} finally {
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}
備註:只需要修改上傳的伺服器地址、用戶名、密碼即可進行伺服器訪問上傳。根據實際需要修改即可。

E. 怎麼用Java實現FTP上傳

sun.net.ftp.FtpClient.,該類庫主要提供了用於建立FTP連接的類。利用這些類的方法,編程人員可以遠程登錄到FTP伺服器,列舉該伺服器上的目錄,設置傳輸協議,以及傳送文件。FtpClient類涵蓋了幾乎所有FTP的功能,FtpClient的實例變數保存了有關建立"代理"的各種信息。下面給出了這些實例變數:
public static boolean useFtpProxy
這個變數用於表明FTP傳輸過程中是否使用了一個代理,因此,它實際上是一個標記,此標記若為TRUE,表明使用了一個代理主機。
public static String ftpProxyHost
此變數只有在變數useFtpProxy為TRUE時才有效,用於保存代理主機名。
public static int ftpProxyPort此變數只有在變數useFtpProxy為TRUE時才有效,用於保存代理主機的埠地址。
FtpClient有三種不同形式的構造函數,如下所示:
1、public FtpClient(String hostname,int port)
此構造函數利用給出的主機名和埠號建立一條FTP連接。
2、public FtpClient(String hostname)
此構造函數利用給出的主機名建立一條FTP連接,使用默認埠號。
3、FtpClient()
此構造函數將創建一FtpClient類,但不建立FTP連接。這時,FTP連接可以用openServer方法建立。
一旦建立了類FtpClient,就可以用這個類的方法來打開與FTP伺服器的連接。類ftpClient提供了如下兩個可用於打開與FTP伺服器之間的連接的方法。
public void openServer(String hostname)
這個方法用於建立一條與指定主機上的FTP伺服器的連接,使用默認埠號。
public void openServer(String host,int port)
這個方法用於建立一條與指定主機、指定埠上的FTP伺服器的連接。
打開連接之後,接下來的工作是注冊到FTP伺服器。這時需要利用下面的方法。
public void login(String username,String password)
此方法利用參數username和password登錄到FTP伺服器。使用過Intemet的用戶應該知道,匿名FTP伺服器的登錄用戶名為anonymous,密碼一般用自己的電子郵件地址。
下面是FtpClient類所提供的一些控制命令。
public void cd(String remoteDirectory):該命令用於把遠程系統上的目錄切換到參數remoteDirectory所指定的目錄。
public void cdUp():該命令用於把遠程系統上的目錄切換到上一級目錄。
public String pwd():該命令可顯示遠程系統上的目錄狀態。
public void binary():該命令可把傳輸格式設置為二進制格式。
public void ascii():該命令可把傳輸協議設置為ASCII碼格式。
public void rename(String string,String string1):該命令可對遠程系統上的目錄或者文件進行重命名操作。
除了上述方法外,類FtpClient還提供了可用於傳遞並檢索目錄清單和文件的若干方法。這些方法返回的是可供讀或寫的輸入、輸出流。下面是其中一些主要的方法。
public TelnetInputStream list()
返回與遠程機器上當前目錄相對應的輸入流。
public TelnetInputStream get(String filename)
獲取遠程機器上的文件filename,藉助TelnetInputStream把該文件傳送到本地。
public TelnetOutputStream put(String filename)
以寫方式打開一輸出流,通過這一輸出流把文件filename傳送到遠程計算機

package myUtil;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

/**
* ftp上傳,下載

*
* @author why 2009-07-30
*
*/
public class FtpUtil {
private String ip = "";
private String username = "";
private String password = "";
private int port = -1;
private String path = "";
FtpClient ftpClient = null;
OutputStream os = null;
FileInputStream is = null;
public FtpUtil(String serverIP, String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
}
public FtpUtil(String serverIP, int port, String username, String password) {
this.ip = serverIP;
this.username = username;
this.password = password;
this.port = port;
}
/**
* 連接ftp伺服器
*
* @throws IOException
*/
public boolean connectServer() {
ftpClient = new FtpClient();
try {
if (this.port != -1) {
ftpClient.openServer(this.ip, this.port);
} else {
ftpClient.openServer(this.ip);
}
ftpClient.login(this.username, this.password);
if (this.path.length() != 0) {
ftpClient.cd(this.path);// path是ftp服務下主目錄的子目錄
}
ftpClient.binary();// 用2進制上傳、下載
System.out.println("已登錄到\"" + ftpClient.pwd() + "\"目錄");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 斷開與ftp伺服器連接
*
* @throws IOException
*/
public boolean closeServer() {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
if (ftpClient != null) {
ftpClient.closeServer();
}
System.out.println("已從伺服器斷開");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
/**
* 檢查文件夾在當前目錄下是否存在
*
* @param dir
*@return
*/
private boolean isDirExist(String dir) {
String pwd = "";
try {
pwd = ftpClient.pwd();
ftpClient.cd(dir);
ftpClient.cd(pwd);
} catch (Exception e) {
return false;
}
return true;
}
/**
* 在當前目錄下創建文件夾
*
* @param dir
* @return
* @throws Exception
*/
private boolean createDir(String dir) {
try {
ftpClient.ascii();
StringTokenizer s = new StringTokenizer(dir, "/"); // sign
s.countTokens();
String pathName = ftpClient.pwd();
while (s.hasMoreElements()) {
pathName = pathName + "/" + (String) s.nextElement();
try {
ftpClient.sendServer("MKD " + pathName + "\r\n");
} catch (Exception e) {
e = null;
return false;
}
ftpClient.readServerResponse();
}
ftpClient.binary();
return true;
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
}
/**
* ftp上傳 如果伺服器段已存在名為filename的文件夾,該文件夾中與要上傳的文件夾中同名的文件將被替換
*
* @param filename
* 要上傳的文件(或文件夾)名
* @return
* @throws Exception
*/
public boolean upload(String filename) {
String newname = "";
if (filename.indexOf("/") > -1) {
newname = filename.substring(filename.lastIndexOf("/") + 1);
} else {
newname = filename;
}
return upload(filename, newname);
}
/**
* ftp上傳 如果伺服器段已存在名為newName的文件夾,該文件夾中與要上傳的文件夾中同名的文件將被替換
*
* @param fileName
* 要上傳的文件(或文件夾)名
* @param newName
* 伺服器段要生成的文件(或文件夾)名
* @return
*/
public boolean upload(String fileName, String newName) {
try {
String savefilename = new String(fileName.getBytes("GBK"),
"GBK");
File file_in = new File(savefilename);// 打開本地待長傳的文件
if (!file_in.exists()) {
throw new Exception("此文件或文件夾[" + file_in.getName() + "]有誤或不存在!");
}
if (file_in.isDirectory()) {
upload(file_in.getPath(), newName, ftpClient.pwd());
} else {
uploadFile(file_in.getPath(), newName);
}
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
return true;
} catch (Exception e) {
e.printStackTrace();
System.err.println("Exception e in Ftp upload(): " + e.toString());
return false;
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 真正用於上傳的方法
*
* @param fileName
* @param newName
* @param path
* @throws Exception
*/
private void upload(String fileName, String newName, String path)
throws Exception {
String savefilename = new String(fileName.getBytes("ISO-8859-1"), "GBK");
File file_in = new File(savefilename);// 打開本地待長傳的文件
if (!file_in.exists()) {
throw new Exception("此文件或文件夾[" + file_in.getName() + "]有誤或不存在!");
}
if (file_in.isDirectory()) {
if (!isDirExist(newName)) {
createDir(newName);
}
ftpClient.cd(newName);
File sourceFile[] = file_in.listFiles();
for (int i = 0; i < sourceFile.length; i++) {
if (!sourceFile[i].exists()) {
continue;
}
if (sourceFile[i].isDirectory()) {
this.upload(sourceFile[i].getPath(), sourceFile[i]
.getName(), path + "/" + newName);
} else {
this.uploadFile(sourceFile[i].getPath(), sourceFile[i]
.getName());
}
}
} else {
uploadFile(file_in.getPath(), newName);
}
ftpClient.cd(path);
}
/**
* upload 上傳文件
*
* @param filename
* 要上傳的文件名
* @param newname
* 上傳後的新文件名
* @return -1 文件不存在 >=0 成功上傳,返迴文件的大小
* @throws Exception
*/
public long uploadFile(String filename, String newname) throws Exception {
long result = 0;
TelnetOutputStream os = null;
FileInputStream is = null;
try {
java.io.File file_in = new java.io.File(filename);
if (!file_in.exists())
return -1;
os = ftpClient.put(newname);
result = file_in.length();
is = new FileInputStream(file_in);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
} finally {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
}
return result;
}
/**
* 從ftp下載文件到本地
*
* @param filename
* 伺服器上的文件名
* @param newfilename
* 本地生成的文件名
* @return
* @throws Exception
*/
public long downloadFile(String filename, String newfilename) {
long result = 0;
TelnetInputStream is = null;
FileOutputStream os = null;
try {
is = ftpClient.get(filename);
java.io.File outfile = new java.io.File(newfilename);
os = new FileOutputStream(outfile);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
result = result + c;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 取得相對於當前連接目錄的某個目錄下所有文件列表
*
* @param path
* @return
*/
public List getFileList(String path) {
List list = new ArrayList();
DataInputStream dis;
try {
dis = new DataInputStream(ftpClient.nameList(this.path + path));
String filename = "";
while ((filename = dis.readLine()) != null) {
list.add(filename);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) {
FtpUtil ftp = new FtpUtil("192.168.11.11", "111", "1111");
ftp.connectServer();
boolean result = ftp.upload("C:/Documents and Settings/ipanel/桌面/java/Hibernate_HQL.docx", "amuse/audioTest/music/Hibernate_HQL.docx");
System.out.println(result ? "上傳成功!" : "上傳失敗!");
ftp.closeServer();
/**
* FTP遠程命令列表 USER PORT RETR ALLO DELE SITE XMKD CDUP FEAT PASS PASV STOR
* REST CWD STAT RMD XCUP OPTS ACCT TYPE APPE RNFR XCWD HELP XRMD STOU
* AUTH REIN STRU SMNT RNTO LIST NOOP PWD SIZE PBSZ QUIT MODE SYST ABOR
* NLST MKD XPWD MDTM PROT
* 在伺服器上執行命令,如果用sendServer來執行遠程命令(不能執行本地FTP命令)的話,所有FTP命令都要加上\r\n
* ftpclient.sendServer("XMKD /test/bb\r\n"); //執行伺服器上的FTP命令
* ftpclient.readServerResponse一定要在sendServer後調用
* nameList("/test")獲取指目錄下的文件列表 XMKD建立目錄,當目錄存在的情況下再次創建目錄時報錯 XRMD刪除目錄
* DELE刪除文件
*/
}
}

F. java中用多線程可以提高 ftp批量上傳的速度嗎

在帶寬足夠的情況,多線程各上傳同的文件,是可以的。。。。。。。

G. java ftp上傳5G以上大文件,怎麼做

java上傳可以使用common-fileupload上傳組件的。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 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);
}

}
}

H. Java 批量大文件上傳下載如何實現

解決這種大文件上傳不太可能用web上傳的方式,只有自己開發插件或是當門客戶端上傳,或者用現有的ftp等。
1)開發一個web插件。用於上傳文件。
2)開發一個FTP工具,不用web上傳。
3)用現有的FTP工具。
下面是幾款不錯的插件,你可以試試:
1)Jquery的uploadify插件。具體使用。你可以看幫助文檔。

I. 用java完成圖片多張批量上傳的功能,還有就是後台的應該怎麼處理上傳的照片。

環境准備

1. 下載並安裝Tomcat(已經有很多關於Tomcat安裝以及使用的文章,在這里不再介紹);

2. 下載File upload的jar包commons-fileupload-1.0-beta-1.jar,並將該文件拷貝到{$TOMCAT}/common/lib目錄下(其中{$TOMCAT}為Tomcat的安裝目錄);

3. 由於Fileupload子項目同時要用到另外一個項目commons-Beanutils,所以必須下載Beanutils,並將解壓後的文件commons-beanutils.jar拷貝到{$TOMCAT}/common/lib目錄下。

開發文件上傳頁面

文件上傳的界面如圖1所示。為了增加效率我們設計了三個文件域,同時上傳三個文件。
圖1 文件上傳界面

頁面的HTML代碼如下:

<html>
<head>
<title>文件上傳演示</title>
</head>
<body bgcolor=「#FFFFFF」text=「#000000」 leftmargin=「0」topmargin=「40」marginwidth=「0」 marginheight=「0」>
<center>
<h1>文件上傳演示</h1>
<form name=「uploadform」method=「POST」 action=「save.jsp」ENCTYPE=「multipart/form-data」>
<table border=「1」width=「450」cellpadding=「4」 cellspacing=「2」bordercolor=「#9BD7FF」>
<tr><td width=「100%」colspan=「2」>
文件1:<input name=「file1」size=「40」type=「file」>
</td></tr>
<tr><td width=「100%」colspan=「2」>
文件2:<input name=「file2」size=「40」type=「file」>
</td></tr>
<tr><td width=「100%」colspan=「2」>
文件3:<input name=「file3」size=「40」type=「file」>
</td></tr>
</table>
<br/><br/>
<table>
<tr><td align=「center」><input name=「upload」 type=「submit」value=「開始上傳」/></td></tr>
</table>
</form>
</center>
</body>
</html>

代碼中要特別注意的是黑體處。必須保證表單的ENCTYPE屬性值為multipart/form-data,這樣瀏覽器才能正確執行上傳文件的操作。

處理上傳文件信息

由於本文主要是講述如何使用Commons-fileupload,所以為了便於修改、調試,上傳文件的保存使用一個JSP文件來進行處理。我們將瀏覽器上傳來的所有文件保存在一個指定目錄下並在頁面上顯示所有上傳文件的詳細信息。保存頁面處理結果見圖2所示。
圖2 保存頁面

下面來看看save.jsp的代碼:

<%
/**
* 演示文件上傳的處理
* @author <a href=「mailto:[email protected]」>Winter Lau</a>
* @version $Id: save.jsp,v 1.00 2003/03/01 10:10:15
*/
%>
<%@ page language=「java」contentType=「text/html;charset=GBK」%>
<%@ page import=「java.util.*」%>
<%@ page import=「org.apache.commons.fileupload.*」%>
<html>
<head>
<title>保存上傳文件</title>
</head>
<%
String msg = 「」;
FileUpload fu = new FileUpload();
// 設置允許用戶上傳文件大小,單位:位元組
fu.setSizeMax(10000000);
// maximum size that will be stored in memory?
// 設置最多隻允許在內存中存儲的數據,單位:位元組
fu.setSizeThreshold(4096);
// 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬碟的目錄
fu.setRepositoryPath(「C:\\TEMP」);
//開始讀取上傳信息
List fileItems = fu.parseRequest(request);
%>
<body bgcolor=「#FFFFFF」text=「#000000」 leftmargin=「0」topmargin=「40」marginwidth=「0」 marginheight=「0」>
<font size=「6」color=「blue」>文件列表:</font>
<center>
<table cellpadding=0 cellspacing=1 border=1 width=「100%」>
<tr>
<td bgcolor=「#008080」>文件名</td>
<td bgcolor=「#008080」>大小</td>
</tr>
<%
// 依次處理每個上傳的文件
Iterator iter = fileItems.iterator();
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;
%>
<tr>
<td><%=item.getName()%></td>
<td><%=item.getSize()%></td>
</tr>
<%
//保存上傳的文件到指定的目錄
name = name.replace(『:』,『_』);
name = name.replace(『\\』,『_』);
item.write(「F:\\」+ name);
}
}
%>
</table>

<br/><br/>
<a href=「upload.html」>返回上傳頁面</a>
</center>
</body>
</html>

在這個文件中需要注意的是FileUpload對象的一些參數值的意義,如下面代碼所示的三個參數sizeMax、sizeThreshold、repositoryPath:

FileUpload fu = new FileUpload();
// 設置允許用戶上傳文件大小,單位:位元組
fu.setSizeMax(10000000);
// maximum size that will be stored in memory?
// 設置最多隻允許在內存中存儲的數據,單位:位元組
fu.setSizeThreshold(4096);
// 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬碟的目錄
fu.setRepositoryPath(「C:\\TEMP」);

這3個參數的意義分別為:

SizeMax 用來設置上傳文件大小的最大值,一旦用戶上傳的文件大小超過該值時將會拋出一個FileUploadException異常,提示文件太大;

SizeThreshold 設置內存中緩沖區的大小,一旦文件的大小超過該值的時候,程序會自動將其它數據存放在repositoryPath指定的目錄下作為緩沖。合理設置該參數的值可以保證伺服器穩定高效的運行;

RepositoryPath 指定緩沖區目錄。

使用注意事項
從實際應用的結果來看該模塊能夠穩定高效的工作。其中參數SizeThreshold的值至關重要,設置太大會佔用過多的內存,設置太小會頻繁使用硬碟作為緩沖以致犧牲性能。因此,設置該值時要根據用戶上傳文件大小分布情況來設定。例如大部分文件大小集中在100KB左右,則可以使用100KB作為該參數的值,當然了再大就不合適了。使用commons-fileupload來處理HTTP文件上傳的功能模塊很小,但是值得研究的東西很多。

J. java 實現ftp上傳如何創建文件夾

這個功能我也剛寫完,不過我也是得益於同行,現在我也把自己的分享給大家,希望能對大家有所幫助,因為自己的項目不涉及到創建文件夾,也僅作分享,不喜勿噴謝謝!

interface:
packagecom.sunline.bank.ftputil;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importorg.apache.commons.net.ftp.FTPClient;

publicinterfaceIFtpUtils{
/**
*ftp登錄
*@paramhostname主機名
*@paramport埠號
*@paramusername用戶名
*@parampassword密碼
*@return
*/
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword);
/**
*上穿文件
*@paramhostname主機名
*@paramport埠號
*@paramusername用戶名
*@parampassword密碼
*@paramfpathftp路徑
*@paramlocalpath本地路徑
*@paramfileName文件名
*@return
*/
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName);
/**
*批量下載文件
*@paramhostname
*@paramport
*@paramusername
*@parampassword
*@paramfpath
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改成的文件名
*@return
*/
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames);
/**
*修改文件名
*@paramlocalpath
*@paramfileName源文件名
*@paramfilenames需要修改的文件名
*/
(Stringlocalpath,StringfileName,Stringfilenames);
/**
*關閉流連接、ftp連接
*@paramftpClient
*@parambufferRead
*@parambuffer
*/
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer);
}

impl:
packagecom.sunline.bank.ftputil;

importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;
importcommon.Logger;

{
privatestaticLoggerlog=Logger.getLogger(FtpUtilsImpl.class);
FTPClientftpClient=null;
Integerreply=null;

@Override
publicFTPClientloginFtp(Stringhostname,Integerport,Stringusername,Stringpassword){
ftpClient=newFTPClient();
try{
ftpClient.connect(hostname,port);
ftpClient.login(username,password);
ftpClient.setControlEncoding("utf-8");
reply=ftpClient.getReplyCode();
ftpClient.setDataTimeout(60000);
ftpClient.setConnectTimeout(60000);
//設置文件類型為二進制(避免解壓縮文件失敗)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
//開通數據埠傳輸數據,避免阻塞
ftpClient.enterLocalActiveMode();
if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
log.error("連接FTP失敗,用戶名或密碼錯誤");
}else{
log.info("FTP連接成功");
}
}catch(Exceptione){
if(!FTPReply.isPositiveCompletion(reply)){
try{
ftpClient.disconnect();
}catch(IOExceptione1){
log.error("登錄FTP失敗,請檢查FTP相關配置信息是否正確",e1);
}
}
}
returnftpClient;
}

@Override
@SuppressWarnings("resource")
(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName){
booleanflag=false;
ftpClient=loginFtp(hostname,port,username,password);
BufferedInputStreambuffer=null;
try{
buffer=newBufferedInputStream(newFileInputStream(localpath+fileName));
ftpClient.changeWorkingDirectory(fpath);
fileName=newString(fileName.getBytes("utf-8"),ftpClient.DEFAULT_CONTROL_ENCODING);
if(!ftpClient.storeFile(fileName,buffer)){
log.error("上傳失敗");
returnflag;
}
buffer.close();
ftpClient.logout();
flag=true;
returnflag;
}catch(Exceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,null,buffer);
log.info("文件上傳成功");
}
returnfalse;
}

@Override
publicbooleandownloadFileList(Stringhostname,Integerport,Stringusername,Stringpassword,Stringfpath,Stringlocalpath,StringfileName,Stringfilenames){
ftpClient=loginFtp(hostname,port,username,password);
booleanflag=false;
=null;
if(fpath.startsWith("/")&&fpath.endsWith("/")){
try{
//切換到當前目錄
this.ftpClient.changeWorkingDirectory(fpath);
this.ftpClient.enterLocalActiveMode();
FTPFile[]ftpFiles=this.ftpClient.listFiles();
for(FTPFilefiles:ftpFiles){
if(files.isFile()){
System.out.println("=================="+files.getName());
FilelocalFile=newFile(localpath+"/"+files.getName());
bufferRead=newBufferedOutputStream(newFileOutputStream(localFile));
ftpClient.retrieveFile(files.getName(),bufferRead);
bufferRead.flush();
}
}
ftpClient.logout();
flag=true;

}catch(IOExceptione){
e.printStackTrace();
}finally{
closeFtpConnection(ftpClient,bufferRead,null);
log.info("文件下載成功");
}
}
modifiedLocalFileName(localpath,fileName,filenames);
returnflag;
}

@Override
(Stringlocalpath,StringfileName,Stringfilenames){
Filefile=newFile(localpath);
File[]fileList=file.listFiles();
if(file.exists()){
if(null==fileList||fileList.length==0){
log.error("文件夾是空的");
}else{
for(Filedata:fileList){
Stringorprefix=data.getName().substring(0,data.getName().lastIndexOf("."));
Stringprefix=fileName.substring(0,fileName.lastIndexOf("."));
System.out.println("index==="+orprefix+"prefix==="+prefix);
if(orprefix.contains(prefix)){
booleanf=data.renameTo(newFile(localpath+"/"+filenames));
System.out.println("f============="+f);
}else{
log.error("需要重命名的文件不存在,請檢查。。。");
}
}
}
}
}


@Override
publicvoidcloseFtpConnection(FTPClientftpClient,,BufferedInputStreambuffer){
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=bufferRead){
try{
bufferRead.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
if(null!=buffer){
try{
buffer.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}


publicstaticvoidmain(String[]args)throwsIOException{
Stringhostname="xx.xxx.x.xxx";
Integerport=21;
Stringusername="edwftp";
Stringpassword="edwftp";
Stringfpath="/etl/etldata/back/";
StringlocalPath="C:/Users/Administrator/Desktop/ftp下載/";
StringfileName="test.txt";
Stringfilenames="ok.txt";
FtpUtilsImplftp=newFtpUtilsImpl();
/*ftp.modifiedLocalFileName(localPath,fileName,filenames);*/
ftp.downloadFileList(hostname,port,username,password,fpath,localPath,fileName,filenames);
/*ftp.uploadLocalFilesToFtp(hostname,port,username,password,fpath,localPath,fileName);*/
/*ftp.modifiedLocalFileName(localPath);*/
}
}
熱點內容
sql全形轉半形 發布:2024-10-07 08:25:00 瀏覽:778
公眾伺服器配置是什麼 發布:2024-10-07 08:17:11 瀏覽:492
為什麼伺服器貴嗎 發布:2024-10-07 08:16:37 瀏覽:641
為什麼伺服器的引導分區會損壞 發布:2024-10-07 07:54:07 瀏覽:672
安卓社交源碼 發布:2024-10-07 07:16:12 瀏覽:949
python兩個list合並 發布:2024-10-07 07:12:02 瀏覽:870
迅雷文件夾加密 發布:2024-10-07 07:03:00 瀏覽:952
dns伺服器地址是多少 發布:2024-10-07 06:53:42 瀏覽:176
論壇php程序 發布:2024-10-07 06:52:16 瀏覽:581
2005資料庫恢復 發布:2024-10-07 06:21:49 瀏覽:381