ftp上传程序(JAVA)

一共有三个程序,两个JSP,一个JAVA

1,send.jsp 前台页面

<%@ page contentType="text/html;charset=gb2312"%>
<%@ page language="java" import="net.clore.db.*"%>
<%@ page import="java.util.*"%>  
<%@ include file="../incs/config.jsp"%>
<html>
<head>
<title>彩信发送--导入</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link rel="stylesheet" href="../images/style.css" type="text/css">
</head>
<body bgcolor="#FFFFFF" text="#000000" topmargin="0" leftmargin="0">
<table border="0" width="100%" id="table1" height="55">
 <tr>
  <td>&nbsp;
  <font color="red">当前位置: -&gt; </font><font color="#FF0000">发送彩信</font></td>
 </tr>
</table>
<div align="center">
 <table border="0" width="446" id="table2" cellspacing="0" cellpadding="0">
  <tr>
   <td background="../images/edit/edit-04.gif" height="18"></td>
  </tr>
  <tr>
   <td background="../images/edit/edit-02.gif" height="86">
   <div align="center">
    <table border="0" width="80%" id="table3" cellspacing="0" cellpadding="10">
     <tr>
      <td>
      <div align="center">
<font size="3">
<b>方法一:导入彩信文件</b></font></div>
      <div align="center">
<hr noshade size="1"></div>
 
 <!-- 文件上传 -->    
<form name="Form1" enctype="multipart/form-data" method="post" action="send_x.jsp">
 <p>请选择要导入的文件: <input type="file" name="file1" size="30" maxlength="30"></p>
 <p><input type="file" name="file2" size="30" maxlength="30"></p>
 <p>请选择图片大小<br>
 <select name="filesize">
        <option value="1" >128 x 128</option>
        <option value="2" >100 x 100</option>  
        <option value="3" >96 x 96</option>
        <option value="4" >80 x 80</option>
    </select>
    </p>
 <!-- <p>文件名:<br><input type="text" name="filename" value="" size="30" maxlength="30"></p>  -->
 <p> <input type="submit" class="myButton" value=" 上传 " onClick="this.disabled"> <input type="reset" class="myButton" value="清除"> </p>
</form>
      <p>注意:导入的文件大小不要超过20M。</td>
     </tr>
    </table>
   </div>
   </td>
  </tr>
 </table>
<p>
 <table border="0" width="446" id="table2" cellspacing="0" cellpadding="0">
  <tr>
   <td background="../images/edit/edit-04.gif" height="18"></td>
  </tr>
  <tr>
   <td background="../images/edit/edit-02.gif" height="86">
   <div align="center">
    <table border="0" width="80%" id="table3" cellspacing="0" cellpadding="10">
     <tr>
      <td>
      <div align="center">
<font size="3">
<b>方法二:手动输入彩信内容</b></font></div>
      <div align="center">
<hr noshade size="1"></div>
<form name="main" enctype="multipart/form-data" method="post" action="send_x.jsp">
    <table cellspacing="5">
     <tr>
      <td align="left" valign="top" nowrap>文件名:</td>
      <td><input type="text" name="filename" maxlength="30"></td>
        <tr>
          <td align="right" valign="top" nowrap>短信内容:</br></br>
          <td align="left" valign="top"><textarea name="cont" cols="40" rows="6" class="myInput"></textarea></td>
        </tr>
 </table>
<p> <input type="submit" class="myButton" value=" 上传 " onClick="this.disabled"> <input type="reset" class="myButton" value="清除"> </p>
</form>
      <p>短信内容不能为空。</td>
     </tr>
    </table>
   </div>
   </td>
  </tr>
  <tr>
   <td background="../images/edit/edit-03.gif" height="18"> </td>
  </tr>
 </table>
</div>
<script language="javascript">
</script>
</body>
</html>
<%out.flush();%> 

2,send_x.jsp

<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<%@ page import="net.clore.ftpserver.ApacheFtpClient"%>
<%@ include file="../incs/config.jsp"%>
<%@ page import="java.io.*"%>
<%@ page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%
   String filename = "";
            String saveDirectory = "/var/www/resin-www/temp/ftptest/client/";
            String destDirectory = "/var/www/resin-www/temp/ftptest/server/";
            String s_ip = "192.168.1.231";
            String s_user = "sms-www";
            String s_password = "sjb2005";
            //最大上传5M
            int maxPostSize = 5 * 1024 * 1024;
            // 产一个新的MultipartRequest 的物件,multi
            if (!request.getMethod().equals("POST"))
                return;
   
            MultipartRequest multi = new MultipartRequest(request,
                    saveDirectory, maxPostSize, "iso-8859-1",
                    new DefaultFileRenamePolicy());
         String filesize = multi.getParameter("filesize");
            String cont = multi.getParameter("cont");
           
            ApacheFtpClient ftp = new ApacheFtpClient();
            ftp.connectFtpServer(s_ip, s_user, s_password);
            TreeMap map = new TreeMap();
            if (cont != null) {        //第二种方式
             filename = multi.getParameter("filename")+".txt";
                FileWriter filewrite = new FileWriter(saveDirectory + filename );
                filewrite.write(cont);
                filewrite.close();
                map.put(saveDirectory + filename, destDirectory);
                ftp.transferAllFiles(map);
            } else {                  //第一种方式
                Enumeration filesname = multi.getFileNames();
                while (filesname.hasMoreElements()) {
                 map = new TreeMap();
                    String name = (String) filesname.nextElement();
                    filename = multi.getFilesystemName(name);
                    //文件名可能为空,即当用户只上传一个文件时
                    if(filename!=null){
                     if(filename.endsWith("gif")){  //图片
                      ftp.transferPhoto(saveDirectory + filename,filesize);
                     }else{                         //文件
                      map.put(saveDirectory + filename, destDirectory);
                      ftp.transferAllFiles(map);
                     }
                 }
                }
            }
            %>
<html>
 <head>
  <title>彩信发送</title>
  <link rel="stylesheet" href="../images/style.css" _fcksavedurl=""../images/style.css"" type="text/css">
  <meta http-equiv="Content-Type" content="text/html; charset=GBK">
  <meta http-equiv="refresh" content="3;url=send.jsp">
 </head>
 <body leftmargin="0" topmargin="0">
  <table width="100%" height="54" border="0" cellpadding="0" cellspacing="0" background="../images/online_tit.gif">
   <tr>
    <td>
     &nbsp;&nbsp; <font color="red">彩信发送 -&gt; 发送结果</font>
    </td>
   </tr>
  </table>
  <table width="<%=cfgTableWidth%>" border="0" align="center">
   <tr>
    <td align="center">
     彩信发送成功(3秒后自动返回)
    </td>
   </tr>
   <tr>
    <td align="center">
     <a href="send.jsp"><%=sCaptionBack%></a>
    </td>
   </tr>
  </table>
  <table width="446" border="0" align="center" cellpadding="0" cellspacing="0">
   <tr>
    <br>
   </tr>
   <tr>
    <br>
    <div align="center">
     <table width="76%" cellspacing="5">
      <tr>
       <td colspan="2" align="left">
        <%//取得所有上传之档案输入形态名称
        %>
       </td>
      </tr>
     </table>
    </div>
   </tr>
   <tr>

3,ApacheFtpClient.java

package net.clore.ftpserver;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import javax.imageio.ImageIO;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTP;

public class ApacheFtpClient extends TimerTask {

    public static final int INTERVAL = 30000;

    private boolean flag = false;

    private String filename = "";

    private static FTPClient ftpTool = null;

    // totalTime为空闲时间,当totalTime超过2分钟时,程序主动断开与ftp服务器的连接
    private static int totalTime = 0;
    static {
        Timer time = new Timer();
        time.schedule(new ApacheFtpClient(), new Date(), 30000);
    }

    // 连接到ftp server
    public void connectFtpServer(String s_ip, String s_user, String s_password) {
        try {
            if (ftpTool == null || !ftpTool.isConnected()) {
                System.out.println("prepare to connect!");
                ftpTool = new FTPClient();
                ftpTool.connect(s_ip);
                ftpTool.login(s_user, s_password);
                ftpTool.setFileType(FTP.BINARY_FILE_TYPE);
                ftpTool.enterLocalActiveMode();
                // 35秒超时
                ftpTool.setSoTimeout(35000);
                System.out.println("login succ!");
                totalTime = 0;
            } else {
                if (ftpTool == null)
                    System.out.println("ftpTool is null ");
                if (ftpTool.isConnected())
                    System.out.println("ftp is connect "
                            + ftpTool.isConnected());
            }
        } catch (Exception e) {
            System.out.println("can not login ftp server");
            e.printStackTrace();
        }
    }

    // 断开与ftp server的连接
    public void disconnFtpServer() {
        try {
            ftpTool.logout();
            ftpTool.disconnect();
            totalTime = 0;
            System.out.println("disconn succ!");
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            ftpTool = null;
        }
    }

    /*
     * 执行由参数指定的ftp传输任务。 传输任务的格式为TreeMap(本地全路径文件名, 远程文件名)
     */
    public void transferAllFiles(TreeMap filesTransferInfoObj) throws Exception {
        Iterator itor = filesTransferInfoObj.entrySet().iterator();
        while (itor.hasNext()) {
            Map.Entry e = (Map.Entry) itor.next();
            String s_localFileName = e.getKey().toString();
            String s_destDirectory = e.getValue().toString();
            filename = s_localFileName.substring(s_localFileName
                    .lastIndexOf("/") + 1);// 取得文件名
            try {
                ftpTool.changeWorkingDirectory(s_destDirectory);
                ftpTool.storeFile(filename, new BufferedInputStream(
                        new FileInputStream(s_localFileName)));
                totalTime = 0;
                System.out.println(filename + " tranfer finished");
            } catch (Exception ex) {
                System.out.println("/t     failed.   |   " + ex);
            }
        }
    }

    /*
     * 图片处理 
     * @param srcImageFile 图片的源路径
     * @param scale 图片尺寸
     */
    public void transferPhoto(String srcImageFile, String scale) {
        int size = 0;
        TreeMap map = new TreeMap();
        map.put(srcImageFile, srcImageFile);
        if (scale.equals("1")) {
            size = 128;
        } else if (scale.equals("2")) {
            size = 100;
        } else if (scale.equals("3")) {
            size = 96;
        } else {
            size = 80;
        }
        try {
            BufferedImage src = ImageIO.read(new File(srcImageFile)); // 读入文件
            int width = src.getWidth(); // 得到源图宽
            int height = src.getHeight(); // 得到源图长
            width = size;
            height = size;
            Image image = src.getScaledInstance(width, height,
                    Image.SCALE_DEFAULT);
            BufferedImage tag = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            ImageIO.write(tag, "JPEG", new File(srcImageFile));// 输出到文件流
            map.put(srcImageFile, "/var/www/resin-www/temp/ftptest/server");
            //使用transferAllFiles方法上传图片
            this.transferAllFiles(map);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void run() {
        try {
            if (ftpTool != null && ftpTool.isConnected()) {
                if (flag == false) {
                    flag = true;
                }
                // 累加
                totalTime += INTERVAL;
                // 如果totalTime超过2分钟就断开ftp连接
                if (totalTime >= 120000) {
                    this.disconnFtpServer();
                    totalTime = 0;
                } else {
                    // 发送noop命令以保持连接
                    ftpTool.noop();
                    System.out.println("is Connected " + ftpTool.isConnected());
                }
                System.out.println(totalTime);
            } else if (flag) {
                flag = false;
                System.out.println("no connection");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值