设为首页 收藏本站
查看: 1192|回复: 0

[经验分享] ftp 文件上传 文件损坏

[复制链接]

尚未签到

发表于 2016-6-8 10:43:40 | 显示全部楼层 |阅读模式
  


  
  这里演示的是配置好ftp服务器后,通过java程序读取硬盘文件上传(相对于通过网页控件<input type="file">获得文件上传)。首先到apache上下载 common net 包,
然后参考http://www.iyunv.com/topic/139300或者http://www.iyunv.com/topic/173786 提供的代码:
 
具体的操作类:
  
  

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 java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
public class FTPUtil {
private FTPClient ftpClient;
public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;
public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;
// path should not the path from root index
// or some FTP server would go to root as '/'.
public void connectServer(Properties ftpConfig) throws SocketException,
IOException {
String server = ftpConfig.getProperty("server");
String user = ftpConfig.getProperty("username");
String password = ftpConfig.getProperty("password");
int port = 21;
String location = ftpConfig.getProperty("location");
connectServer(server, port, user, password, location);
}

public void connectServer(String server, int port, String user,
String password, String path) throws SocketException, IOException {
ftpClient = new FTPClient();
ftpClient.connect(server, port);
System.out.println("Connected to " + server + ".");
System.out.println(ftpClient.getReplyCode());
ftpClient.login(user, password);
// Path is the sub-path of the FTP path
if (path.length() != 0) {
ftpClient.changeWorkingDirectory(path);
}
}
//FTP.BINARY_FILE_TYPE | FTP.ASCII_FILE_TYPE
// Set transform type
public void setFileType(int fileType) throws IOException {
ftpClient.setFileType(fileType);
}
//FTP.BINARY_FILE_TYPE | FTP.ASCII_FILE_TYPE
// Set transform type
public void setControlEncoding(String ControlEncoding) throws IOException {
ftpClient.setControlEncoding(ControlEncoding);
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
ftpClient.configure(conf);
}
public void closeServer() throws IOException {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}
//=======================================================================
//==         About directory       =====
// The following method using relative path better.
//=======================================================================
public boolean changeDirectory(String path) throws IOException {
return ftpClient.changeWorkingDirectory(path);
}
public boolean createDirectory(String pathName) throws IOException {
return ftpClient.makeDirectory(pathName);
}
public boolean removeDirectory(String path) throws IOException {
return ftpClient.removeDirectory(path);
}
// delete all subDirectory and files.
public boolean removeDirectory(String path, boolean isAll)
throws IOException {
if (!isAll) {
return removeDirectory(path);
}
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr == null || ftpFileArr.length == 0) {
return removeDirectory(path);
}
//
for (FTPFile ftpFile : ftpFileArr) {
String name = ftpFile.getName();
if (ftpFile.isDirectory()) {
System.out.println("* [sD]Delete subPath ["+path + "/" + name+"]");
removeDirectory(path + "/" + name, true);
} else if (ftpFile.isFile()) {
System.out.println("* [sF]Delete file ["+path + "/" + name+"]");
deleteFile(path + "/" + name);
} else if (ftpFile.isSymbolicLink()) {
} else if (ftpFile.isUnknown()) {
}
}
return ftpClient.removeDirectory(path);
}
// Check the path is exist; exist return true, else false.
public boolean existDirectory(String path) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
for (FTPFile ftpFile : ftpFileArr) {
if (ftpFile.isDirectory()
&& ftpFile.getName().equalsIgnoreCase(path)) {
flag = true;
break;
}
}
return flag;
}
//=======================================================================
//==         About file        =====
// Download and Upload file using
// ftpUtil.setFileType(FtpUtil.BINARY_FILE_TYPE) better!
//=======================================================================
// #1. list & delete operation
// Not contains directory
public List<String> getFileList(String path) throws IOException {
// listFiles return contains directory and file, it's FTPFile instance
// listNames() contains directory, so using following to filer directory.
//String[] fileNameArr = ftpClient.listNames(path);
FTPFile[] ftpFiles= ftpClient.listFiles(path);
List<String> retList = new ArrayList<String>();
if (ftpFiles == null || ftpFiles.length == 0) {
return retList;
}
for (FTPFile ftpFile : ftpFiles) {
if (ftpFile.isFile()) {
retList.add(ftpFile.getName());
}
}
return retList;
}
public boolean deleteFile(String pathName) throws IOException {
return ftpClient.deleteFile(pathName);
}
// #2. upload to ftp server
// InputStream <------> byte[]  simple and See API
public boolean uploadFile(String fileName, String newName)
throws IOException {
boolean flag = false;
InputStream iStream = null;
try {
iStream = new FileInputStream(fileName);
flag = ftpClient.storeFile(newName, iStream);
} catch (IOException e) {
flag = false;
return flag;
} finally {
if (iStream != null) {
iStream.close();
}
closeServer();
}
return flag;
}
public boolean uploadFile(String fileName) throws IOException {
return uploadFile(fileName, fileName);
}
public boolean uploadFile(InputStream iStream, String newName)
throws IOException {
boolean flag = false;
try {
// can execute [OutputStream storeFileStream(String remote)]
// Above method return's value is the local file stream.
flag = ftpClient.storeFile(newName, iStream);
} catch (IOException e) {
flag = false;
return flag;
} finally {
if (iStream != null) {
iStream.close();
}
}
return flag;
}
// #3. Down load
public boolean download(String remoteFileName, String localFileName)
throws IOException {
boolean flag = false;
File outfile = new File(localFileName);
OutputStream oStream = null;
try {
oStream = new FileOutputStream(outfile);
flag = ftpClient.retrieveFile(remoteFileName, oStream);
} catch (IOException e) {
flag = false;
return flag;
} finally {
oStream.close();
}
return flag;
}
public InputStream downFile(String sourceFileName) throws IOException {
return ftpClient.retrieveFileStream(sourceFileName);
}
}
  
  测试类:
  

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Properties;
public class TestUpload {
public static void main(String[] args) {
try {
Properties config = new Properties();
config.setProperty("server", "192.168.17.48");
config.setProperty("username", "admin");
config.setProperty("password", "123456");
config.setProperty("location", "");
FTPUtil client = new FTPUtil();
client.connectServer(config);
//client.setFileType(client.ASCII_FILE_TYPE);
client.setFileType(client.BINARY_FILE_TYPE);
client.setControlEncoding("GBK");
client.uploadFile("D:\\video_1080p\\1080P\\我们Taxi3_WMVHD_Extract.wmv", "Taxi2_WMVHD_Extract.wmv");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

  开始时候没有设定FileType,上传的文件老是略微大于本地文件的大小,而且上传后的文件后的文件无法打开。
  
使用setFileType 设置成BINARY 

 


  
  
public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;
public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;
client.setFileType(client.BINARY_FILE_TYPE);

  
  
  zjumty 同学在他的帖子里对这个问题做了很好的解释:
  写道
  

传输binary文件, 由于FTPClient默认使用ASCII作为传输模式, 所有不能传输二进制文件. 通过
ftp.setFileType(FTP.BINARY_FILE_TYPE)个可以解决这个问题, 但是要在login以后执行. 因为这个方法要向服务器发送"TYPE I"命令.
开始的时候用的是setFileTransferMode, 不过不好使. 它会执行 MODE I命令, 服务器不接受.
  
该问题解决。
  
参考:
  
http://www.iyunv.com/topic/139300
  
http://www.iyunv.com/topic/173786

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-227765-1-1.html 上篇帖子: FTP下载和解析 下篇帖子: Flex使用FTP上传文件
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表