java大文件上传ftp
利用PHP,你总是可以有多种方式来完成某个特定的任务。
我们就拿文件上传举个例子。
当然了,你可以按照传统的方式来使用HTTP文件上传,把文件直接传输到Web服务器磁盘上。
湖北电脑培训http://www.kmbdqn.cn/认为你还可以用更加奇异的方式上传,用FTP协议两步就完成上传:从你的本地硬盘到Web服务器,然后再到FTP服务器。
PHP在本机同时支持FTP和HTTP上传,所以你可以根据自己应用程序的设计需要进行最佳的选择。
使用PHP的FTP函数进行文件传输几乎与使用传统的FTP客户端相同——你会看到连函数的名字都和标准的FTP命令类似。
关于HTTP文件上传的文章已经多得满天飞了,这就是为什么本文有必要把注意力放在基于FTP的文件上传上了(但是在后面给出的例子中,两种方式你都会看到)。
要注意的是,本教程假设你已经安装好了PHP/Apache,而且HTTP文件上传和FTP的函数都已经激活了。
第一步:确信你拥有连接/上传到FTP服务器的权限PHP的FTP函数需要客户端-服务器连接,所以你需要在进行文件上传之前登录到目标服务器上。
你的第一项任务是确信你已经拥有了完成这项任务的信任书。
这一步可能看起来是理所当然的,但是你会惊奇地发现有多少开发人员忘了这么做,结果后来浪费大量的时间来解决因此而出现的问题。
2. JAVA FTP 大文件 上传
把JAVA压缩,用文件分割工具,分割成多个小压缩包,再一个一个上传到FTP。
3. 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);
}
}
}
4. java代码ftp.storefile传送文件,文件太大为什么会突然终止
可能是你的电脑文件系统,FAT32只支持4G以下,
5. java web 大文件上传下载
直接把大文件读取为IO流,之后进行上传下载即可,不用担心文件大,是可以分流下载上传的(setBufferSize(1024))。
举例:
import hkrt.b2b.view.util.Log;
import hkrt.b2b.view.util.ViewUtil;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class CCFCCBFTP {
/**
* 上传文件
*
* @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);
}
}
}
}
/**
*下载文件
*
* @param localFilePath
* @param fileName
* @param routeFilepath
* @return
* @throws Exception
*/
public static String fileDownloadByFtp(String localFilePath, String fileName,String routeFilepath) throws Exception {
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
FileOutputStream fos = null;
FTPClient ftpClient = new FTPClient();
String SFP = System.getProperty("file.separator");
String bl = "false";
try {
Log.info("下载并解密文件开始");
Log.info("连接远程下载服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);
ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);
ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);
// ftpClient.connect(CMBCUtil.CMBCHOSTNAME, 2021);
// ftpClient.login(CMBCUtil.CMBCLOGINNAME, CMBCUtil.CMBCLOGINPASSWORD);
FTPFile[] fs;
ftpClient.makeDirectory(routeFilepath);
ftpClient.changeWorkingDirectory(routeFilepath);
bl = "false";
fs = ftpClient.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
bl = "true";
Log.info("下载文件开始。");
ftpClient.setBufferSize(1024);
// 设置文件类型(二进制)
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
InputStream is = ftpClient.retrieveFileStream(fileName);
bos = new ByteArrayOutputStream(is.available());
byte[] buffer = new byte[1024];
int count = 0;
while ((count = is.read(buffer)) != -1) {
bos.write(buffer, 0, count);
}
bos.flush();
fos = new FileOutputStream(localFilePath+SFP+fileName);
fos.write(bos.toByteArray());
Log.info("下载文件结束:"+localFilePath);
}
}
Log.info("检查文件是否存:"+fileName+" "+bl);
if("false".equals(bl)){
ViewUtil.dataSEErrorPerformedCommon("查询无结果,请稍后再查询。");
return bl;
}
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);
}
}
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
Log.info(e.getLocalizedMessage(), e);
}
}
}
}}
备注:以上方法就实现了流的二进制上传下载转换,只需要将服务器连接部分调整为本地的实际ftp服务用户名和密码即可。
6. java FTP上传 , 服务器卡死
卡死?赶紧换一台配置更好的服务器吧。。。。做为一个服务器商的建议
7. 怎么用JSP把本地的文件夹上传到FTP服务器
前段时间做了一个文件上传ftp功能,你参照一下
package com.ftp.upload;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
public class FTPUpload {
private FTPClient ftpClient = null;
private OutputStream outSteam = null;
/**
* ftp服务器地址
*/
private String hostname = "192.168.1.2";
/**
* ftp服务器端口
*/
int port = 21;
/**
* 登录名
*/
private String username = "admin";
/**
* 登录密码
*/
private String password = "admin";
/**
* 需要访问的远程目录
*/
private String remoteDir = "/home/demo";
public FTPUpload() { }
public FTPUpload(String hostname, int port, String username, String password, String remoteDir){
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
this.remoteDir = remoteDir;
}
/**
* 连接FTP服务器 并登录
* @param hostName FTP服务器hostname
* @param port FTP服务器端口
* @param username FTP登录账号
* @param password FTP登录密码
*/
private FTPClient connectFTPServer() {
try {
//1.创建FTPClient对象
ftpClient = new FTPClient();
//2.连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftpClient.connect(hostname, port); //链接到ftp服务器
// System.out.println("连接到ftp服务器地址 --> ftp://" + hostName + ":" + port + " 成功..开始登录");
//3.判断连接ftp服务器是否成功
int reply = ftpClient.getReplyCode();
// System.out.println("以2开头的返回值就会为真:" + reply);
//以2开头的返回值就会为真
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return null;
}
//4.登录FTP服务器.用户名 密码
ftpClient.login(username, password);
System.out.println("登录成功." );
return ftpClient;
} catch (Exception e) {
e.printStackTrace();
ftpClient = null;
return ftpClient;
}
}
/**
* 向FTP服务器上传文件
* @param filePathName 上传文件的全路径名称
* @return 成功返回true,否则返回false
*/
public boolean uploadFile(String filePathName) {
// 初始表示上传失败
boolean success = false;
try {
// 创建FTPClient对象
ftpClient = connectFTPServer();
//创建文件夹
boolean flag = ftpClient.makeDirectory(remoteDir);
if(flag) {
System.out.println("创建文件夹:" + remoteDir );
}
// 转到指定上传目录
boolean flag0 = ftpClient.changeWorkingDirectory(remoteDir);
// 将上传文件存储到指定目录
if(filePathName == null || filePathName.length() == 0){
return success;
}
String filename = filePathName.substring(filePathName.replace("\\", "/").lastIndexOf("/") + 1, filePathName.length());
InputStream input = new FileInputStream(new File(filePathName));
// ftpClient.setBufferSize(1024);
// ftpClient.setControlEncoding("GBK");
// ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);//设置文件类型
boolean flag1 = ftpClient.storeFile(filename, input);
System.out.println("转到指定上传目录:" + flag0 + " 将上传文件存储到指定目录:" + flag1);
input.close(); // 关闭输入流
ftpClient.logout(); // 退出ftp
success = true; // 表示上传成功
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
/**
* 从FTP服务器指定目录下载文件 到本地目录中 OK
* @param fileName 要下载的文件名
* @param localPath 下载后保存到本地的路径
* @param showlist 下载时是否显示列表 ( true 显示 )
* @return
*/
public boolean downFile(String fileName, String localPath, boolean showlist) {
// 初始表示下载失败
boolean success = false;
if(fileName == null || fileName.length() == 0 || localPath == null || localPath.length() == 0){
return success;
}
try {
File file = new File(localPath);
if(!file.isDirectory()){
file.mkdir();
}
// 创建FTPClient对象
ftpClient = connectFTPServer();
// 转到指定下载目录
boolean flag = ftpClient.changeWorkingDirectory(remoteDir);
if(!flag) {
System.out.println("目录:" + remoteDir +"不存在!");
return success;
}
// 列出该目录下所有文件
FTPFile[] remoteFiles = ftpClient.listFiles();
// 遍历所有文件,找到指定的文件
if(showlist){
System.out.println("目录" + remoteDir + "下的文件:");
}
for (FTPFile ftpFile : remoteFiles) {
String name = ftpFile.getName();
if(showlist){
long length = ftpFile.getSize();
String readableLength = FileUtils.byteCountToDisplaySize(length);
System.out.println(name + ":\t\t" + readableLength);
}
if (name.equals(fileName)) {
// 根据绝对路径初始化文件
File localFile = new File(localPath + "/" + name);
// 输出流
OutputStream is = new FileOutputStream(localFile);
// 下载文件
ftpClient.retrieveFile(name, is);
is.close();
}
}
// 退出ftp
ftpClient.logout();
// 下载成功
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
/**
* 显示FTP服务器指定文件夹中的文件及大小 OK
* @return
*/
private boolean showFileList() {
// 初始表示失败
boolean success = false;
try {
ftpClient = connectFTPServer();
FTPFile[] remoteFiles = null;
// 转到指定下载目录
boolean flag = ftpClient.changeWorkingDirectory(remoteDir);
if(!flag) {
System.out.println("目录:" + remoteDir +"不存在!");
return success;
} else{
remoteFiles = ftpClient.listFiles(remoteDir);
System.out.println("目录" + remoteDir + "下的文件:");
}
if(remoteFiles != null) {
for(int i=0;i < remoteFiles.length; i++){
String name = remoteFiles[i].getName();
long length = remoteFiles[i].getSize();
String readableLength = FileUtils.byteCountToDisplaySize(length);
System.out.println(name + ":\t\t" + readableLength);
}
}
// 表示成功
success = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
//使用IO包关闭流
IOUtils.closeQuietly(outSteam);
try {
ftpClient.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
return success;
}
public static void main(String[] args) {
FTPUpload ftp = new FTPUpload();
ftp.uploadFile("c:////test////bgssp.jar");
}
}
8. 用JAVA基于FtpClient类开发时有没有对上传文件时发送数据大小的限制的接口
这个是client程序,所以,你写程序时,判断文件大小、自己限制大小即可
9. java ftpClient怎么上传大文件
ackage downloadMap;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.F
10. java 实现ftp上传下载,windows下和linux下游何区别
packagecom.weixin.util;
importjava.io.File;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.io.PrintWriter;
importjava.io.RandomAccessFile;
importorg.apache.commons.net.PrintCommandListener;
importorg.apache.commons.net.ftp.FTP;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPFile;
importorg.apache.commons.net.ftp.FTPReply;
importcom.weixin.constant.DownloadStatus;
importcom.weixin.constant.UploadStatus;
/**
*支持断点续传的FTP实用类
*@version0.1实现基本断点上传下载
*@version0.2实现上传下载进度汇报
*@version0.3实现中文目录创建及中文文件创建,添加对于中文的支持
*/
publicclassContinueFTP{
publicFTPClientftpClient=newFTPClient();
publicContinueFTP(){
//设置将过程中使用到的命令输出到控制台
this.ftpClient.addProtocolCommandListener(newPrintCommandListener(newPrintWriter(System.out)));
}
/**
*连接到FTP服务器
*@paramhostname主机名
*@paramport端口
*@paramusername用户名
*@parampassword密码
*@return是否连接成功
*@throwsIOException
*/
publicbooleanconnect(Stringhostname,intport,Stringusername,Stringpassword)throwsIOException{
ftpClient.connect(hostname,port);
ftpClient.setControlEncoding("GBK");
if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
if(ftpClient.login(username,password)){
returntrue;
}
}
disconnect();
returnfalse;
}
/**
*从FTP服务器上下载文件,支持断点续传,上传百分比汇报
*@paramremote远程文件路径
*@paramlocal本地文件路径
*@return上传的状态
*@throwsIOException
*/
publicDownloadStatusdownload(Stringremote,Stringlocal)throwsIOException{
//设置被动模式
ftpClient.enterLocalPassiveMode();
//设置以二进制方式传输
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
DownloadStatusresult;
//检查远程文件是否存在
FTPFile[]files=ftpClient.listFiles(newString(remote.getBytes("GBK"),"iso-8859-1"));
if(files.length!=1){
System.out.println("远程文件不存在");
returnDownloadStatus.Remote_File_Noexist;
}
longlRemoteSize=files[0].getSize();
Filef=newFile(local);
//本地存在文件,进行断点下载
if(f.exists()){
longlocalSize=f.length();
//判断本地文件大小是否大于远程文件大小
if(localSize>=lRemoteSize){
System.out.println("本地文件大于远程文件,下载中止");
returnDownloadStatus.Local_Bigger_Remote;
}
//进行断点续传,并记录状态
FileOutputStreamout=newFileOutputStream(f,true);
ftpClient.setRestartOffset(localSize);
InputStreamin=ftpClient.retrieveFileStream(newString(remote.getBytes("GBK"),"iso-8859-1"));
byte[]bytes=newbyte[1024];
longstep=lRemoteSize/100;
longprocess=localSize/step;
intc;
while((c=in.read(bytes))!=-1){
out.write(bytes,0,c);
localSize+=c;
longnowProcess=localSize/step;
if(nowProcess>process){
process=nowProcess;
if(process%10==0)
System.out.println("下载进度:"+process);
//TODO更新文件下载进度,值存放在process变量中
}
}
in.close();
out.close();
booleanisDo=ftpClient.completePendingCommand();
if(isDo){
result=DownloadStatus.Download_From_Break_Success;
}else{
result=DownloadStatus.Download_From_Break_Failed;
}
}else{
OutputStreamout=newFileOutputStream(f);
InputStreamin=ftpClient.retrieveFileStream(newString(remote.getBytes("GBK"),"iso-8859-1"));
byte[]bytes=newbyte[1024];
longstep=lRemoteSize/100;
longprocess=0;
longlocalSize=0L;
intc;
while((c=in.read(bytes))!=-1){
out.write(bytes,0,c);
localSize+=c;
longnowProcess=localSize/step;
if(nowProcess>process){
process=nowProcess;
if(process%10==0)
System.out.println("下载进度:"+process);
//TODO更新文件下载进度,值存放在process变量中
}
}
in.close();
out.close();
booleanupNewStatus=ftpClient.completePendingCommand();
if(upNewStatus){
result=DownloadStatus.Download_New_Success;
}else{
result=DownloadStatus.Download_New_Failed;
}
}
returnresult;
}
/**
*上传文件到FTP服务器,支持断点续传
*@paramlocal本地文件名称,绝对路径
*@paramremote远程文件路径,使用/home/directory1/subdirectory/file.ext按照Linux上的路径指定方式,支持多级目录嵌套,支持递归创建不存在的目录结构
*@return上传结果
*@throwsIOException
*/
publicUploadStatusupload(Stringlocal,Stringremote)throwsIOException{
//设置PassiveMode传输
ftpClient.enterLocalPassiveMode();
//设置以二进制流的方式传输
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("GBK");
UploadStatusresult;
//对远程目录的处理
StringremoteFileName=remote;
if(remote.contains("/")){
remoteFileName=remote.substring(remote.lastIndexOf("/")+1);
//创建服务器远程目录结构,创建失败直接返回
if(CreateDirecroty(remote,ftpClient)==UploadStatus.Create_Directory_Fail){
returnUploadStatus.Create_Directory_Fail;
}
}
//检查远程是否存在文件
FTPFile[]files=ftpClient.listFiles(newString(remoteFileName.getBytes("GBK"),"iso-8859-1"));
if(files.length==1){
longremoteSize=files[0].getSize();
Filef=newFile(local);
longlocalSize=f.length();
if(remoteSize==localSize){
returnUploadStatus.File_Exits;
}elseif(remoteSize>localSize){
returnUploadStatus.Remote_Bigger_Local;
}
//尝试移动文件内读取指针,实现断点续传
result=uploadFile(remoteFileName,f,ftpClient,remoteSize);
//如果断点续传没有成功,则删除服务器上文件,重新上传
if(result==UploadStatus.Upload_From_Break_Failed){
if(!ftpClient.deleteFile(remoteFileName)){
returnUploadStatus.Delete_Remote_Faild;
}
result=uploadFile(remoteFileName,f,ftpClient,0);
}
}else{
result=uploadFile(remoteFileName,newFile(local),ftpClient,0);
}
returnresult;
}
/**
*断开与远程服务器的连接
*@throwsIOException
*/
publicvoiddisconnect()throwsIOException{
if(ftpClient.isConnected()){
ftpClient.disconnect();
}
}
/**
*递归创建远程服务器目录
*@paramremote远程服务器文件绝对路径
*@paramftpClientFTPClient对象
*@return目录创建是否成功
*@throwsIOException
*/
(Stringremote,FTPClientftpClient)throwsIOException{
UploadStatusstatus=UploadStatus.Create_Directory_Success;
Stringdirectory=remote.substring(0,remote.lastIndexOf("/")+1);
if(!directory.equalsIgnoreCase("/")&&!ftpClient.changeWorkingDirectory(newString(directory.getBytes("GBK"),"iso-8859-1"))){
//如果远程目录不存在,则递归创建远程服务器目录
intstart=0;
intend=0;
if(directory.startsWith("/")){
start=1;
}else{
start=0;
}
end=directory.indexOf("/",start);
while(true){
StringsubDirectory=newString(remote.substring(start,end).getBytes("GBK"),"iso-8859-1");
if(!ftpClient.changeWorkingDirectory(subDirectory)){
if(ftpClient.makeDirectory(subDirectory)){
ftpClient.changeWorkingDirectory(subDirectory);
}else{
System.out.println("创建目录失败");
returnUploadStatus.Create_Directory_Fail;
}
}
start=end+1;
end=directory.indexOf("/",start);
//检查所有目录是否创建完毕
if(end<=start){
break;
}
}
}
returnstatus;
}
/**
*上传文件到服务器,新上传和断点续传
*@paramremoteFile远程文件名,在上传之前已经将服务器工作目录做了改变
*@paramlocalFile本地文件File句柄,绝对路径
*@paramprocessStep需要显示的处理进度步进值
*@paramftpClientFTPClient引用
*@return
*@throwsIOException
*/
publicUploadStatusuploadFile(StringremoteFile,FilelocalFile,FTPClientftpClient,longremoteSize)throwsIOException{
UploadStatusstatus;
//显示进度的上传
longstep=localFile.length()/100;
longprocess=0;
longlocalreadbytes=0L;
RandomAccessFileraf=newRandomAccessFile(localFile,"r");
OutputStreamout=ftpClient.appendFileStream(newString(remoteFile.getBytes("GBK"),"iso-8859-1"));
//断点续传
if(remoteSize>0){
ftpClient.setRestartOffset(remoteSize);
process=remoteSize/step;
raf.seek(remoteSize);
localreadbytes=remoteSize;
}
byte[]bytes=newbyte[1024];
intc;
while((c=raf.read(bytes))!=-1){
out.write(bytes,0,c);
localreadbytes+=c;
if(localreadbytes/step!=process){
process=localreadbytes/step;
System.out.println("上传进度:"+process);
//TODO汇报上传状态
}
}
out.flush();
raf.close();
out.close();
booleanresult=ftpClient.completePendingCommand();
if(remoteSize>0){
status=result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed;
}else{
status=result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed;
}
returnstatus;
}
publicstaticvoidmain(String[]args){
ContinueFTPmyFtp=newContinueFTP();
try{
System.err.println(myFtp.connect("10.10.6.236",21,"5","jieyan"));
// myFtp.ftpClient.makeDirectory(newString("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.changeWorkingDirectory(newString("歌曲".getBytes("GBK"),"iso-8859-1"));
// myFtp.ftpClient.makeDirectory(newString("爱你等于爱自己".getBytes("GBK"),"iso-8859-1"));
// System.out.println(myFtp.upload("E:\yw.flv","/yw.flv",5));
// System.out.println(myFtp.upload("E:\爱你等于爱自己.mp4","/爱你等于爱自己.mp4"));
//System.out.println(myFtp.download("/爱你等于爱自己.mp4","E:\爱你等于爱自己.mp4"));
myFtp.disconnect();
}catch(IOExceptione){
System.out.println("连接FTP出错:"+e.getMessage());
}
}
}