sfituhdjyp 发表于 2016-6-8 07:10:00

ftp_文件上传Util

  import java.io.*;
  import java.net.URLEncoder;
  import javax.servlet.http.HttpServletResponse;
  import org.apache.commons.io.IOUtils;
  import org.apache.commons.net.ftp.FTPClient;
  import org.apache.commons.net.ftp.FTPClientConfig;
  import org.apache.commons.net.ftp.FTPReply;
  
  public class FtpLoadUtils {
  /**
  * ftp文件下载
  * @param remotePath 文件路径
  * @param fileName 文件索引名
  * @param fileName2 文件真名
  * @param response 
  * @return
  */
  public static boolean ftpDownFile(String remotePath, String fileName,
  String fileName2,HttpServletResponse response) {
  boolean success = false;
  FTPClient ftp = new FTPClient();
  try {
  int reply;
  // ftp.connect("127.0.0.1");
  ftp.connect("196.128.1.184");
  // 下面三行代码必须要,而且不能改变编码格式
  ftp.setControlEncoding("GBK");
  FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
  conf.setServerLanguageCode("zh");
  // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
  ftp.login("aa", "123");// 登录
  
  reply = ftp.getReplyCode();
  if (!FTPReply.isPositiveCompletion(reply)) {
  ftp.disconnect();
  return success;
  }
  ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
  response.setContentType("APPLICATION/X-msdownload;charset=UTF-8");
  response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName2, "utf-8"));
  // 将文件保存到输出流outputStream中
  OutputStream outputStream=response.getOutputStream();
  //System.out.println(new String(fileName.getBytes("GBK"), "ISO-8859-1"));
  ftp.retrieveFile(new String(fileName.getBytes("GBK"), "ISO-8859-1"), outputStream);
  outputStream.flush();
  outputStream.close();
  
  ftp.logout();
  success = true;
  } catch (IOException e) {
  e.printStackTrace();
  } finally {
  if (ftp.isConnected()) {
  try {
  ftp.disconnect();
  } catch (IOException ioe) {
  }
  }
  }
  return success;
  }
  
  /**
  * ftp文件上传
  * @param srcFile 文件流
  * @param imgmc 文件索引名
  * @param path 文件存储路径
  * @return
  */
  public static boolean upload(File srcFile, String imgmc,String path) {
  boolean result=false;
  FTPClient ftpUploadClient = new FTPClient();
  FileInputStream fis = null;
  try {
  ftpUploadClient.connect("196.128.1.x");
  ftpUploadClient.login("aa", "123");// 正式name
  ftpUploadClient.makeDirectory(path);
  fis = new FileInputStream(srcFile);
  ftpUploadClient.setBufferSize(1024);
  ftpUploadClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  ftpUploadClient.storeFile(path+ imgmc, fis);
  fis.close();
  ftpUploadClient.logout();
  result=true;
  } catch (IOException e) {
  e.printStackTrace();
  } finally {
  IOUtils.closeQuietly(fis);
  if(ftpUploadClient.isConnected()){
  try {
  ftpUploadClient.disconnect();
  } catch (IOException e) {
  e.printStackTrace();
  }
  }
  }
  return result;
  }
  }
页: [1]
查看完整版本: ftp_文件上传Util