textarea 操作

textarea 操作



<%@ page language="java" contentType="text/html; charset=utf-8"

pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>信息管理</title>
<link rel="stylesheet" type="text/css"
href="static/jquery-easyui-1.3.3/themes/default/easyui.css">
<link rel="stylesheet" type="text/css"
href="static/jquery-easyui-1.3.3/themes/icon.css">
<script type="text/javascript"
src="static/jquery-easyui-1.3.3/jquery.min.js"></script>
<script type="text/javascript"
src="static/jquery-easyui-1.3.3/jquery.easyui.min.js"></script>
<script type="text/javascript"
src="static/jquery-easyui-1.3.3/locale/easyui-lang-zh_CN.js"></script>
<!-- 富文本编辑器 -->
<link href="static/js/kindeditor-4.1.10/themes/default/default.css"
type="text/css" rel="stylesheet">
<script type="text/javascript" charset="utf-8"
src="static/js/kindeditor-4.1.10/kindeditor-all-min.js"></script>
<script type="text/javascript" charset="utf-8"
src="static/js/kindeditor-4.1.10/lang/zh_CN.js"></script>










<script type="text/javascript">
var url;


function searchGrade() {
$('#dg').datagrid('load', {
s_truename : $('#s_truename').val()
});
}


function deleteGrade() {
var selectedRows = $("#dg").datagrid('getSelections');
if (selectedRows.length == 0) {
$.messager.alert("系统提示", "请选择要删除的数据!");
return;
}
var strIds = [];
for (var i = 0; i < selectedRows.length; i++) {
strIds.push(selectedRows[i].uid);
}
var ids = strIds.join(",");
$.messager.confirm("系统提示", "您确认要删掉这<font color=red>"
+ selectedRows.length + "</font>条数据吗?", function(r) {
if (r) {
$.post("user/delete.do", {
delIds : ids
}, function(result) {
if (result.success) {
$.messager.alert("系统提示", "您已成功删除<font color=red>"
+ result.delNums + "</font>条数据!");
$("#dg").datagrid("reload");
} else {
$.messager.alert('系统提示', '<font color=red>'
+ selectedRows[result.errorIndex].gradeName
+ '</font>' + result.errorMsg);
}
}, "json");
}
});
}


function openGradeAddDialog() {
$("#dlg").dialog("open").dialog("setTitle", "添加信息");
url = "user/add.do";
}


function openGradeModifyDialog() {
var selectedRows = $("#dg").datagrid('getSelections');
if (selectedRows.length != 1) {
$.messager.alert("系统提示", "请选择一条要编辑的数据!");
return;
}
var row = selectedRows[0];
//alert(row.address);
 KindEditor.html($('#address'), row.address);  //添加一个设置值到 textarea里面
$("#dlg").dialog("open").dialog("setTitle", "编辑信息");
$("#fm").form("load", row);
url = "user/add.do?uid=" + row.uid;
}


function closeGradeDialog() {
$("#dlg").dialog("close");
resetValue();
}


function resetValue() {
$("#loginname").val("");
$("#loginpass").val("");
$("#truename").val("");
$("#tel").val("");
$("#email").val("");
$("#status").val("");
$("#address").val("");
$("#department_id").val("");
$("#progress").val("");
$("#roleid").combobox("setValue", "");
}

function save() {
$("#fm").form("submit", {
url : url,
onSubmit : function() {
if ($('#status').combobox("getValue") == "") {
$.messager.alert("系统提示", "请选择状态");
return false;
}


if ($('#roleid').combobox("getValue") == "") {
$.messager.alert("系统提示", "请选择角色");
return false;
}


//用户名验证
/*
var loginname = $('#loginname').combobox("getValue");
var haha = " ";
$.ajax({
type : 'post',
async : false,
url : 'user/check',
data : {
"loginname" : loginname
},
success : function(data) {
haha = data;
}
});
*/
return $(this).form("validate");
},
success : function(result) {
if (result.errorMsg) {
$.messager.alert("系统提示", result.errorMsg);
return;
} else {
$.messager.alert("系统提示", "保存成功");
resetValue();
$("#dlg").dialog("close");
$("#dg").datagrid("reload");
}
}
});
}
</script>
<script type="text/javascript">
function formatProgress(value){
    if (value){
    var s = '<div style="width:100%;border:1px solid #ccc">' +
    '<div style="width:' + value + '%;background:#009100;color:#fff">' + value + '%' + '</div>'
    '</div>';
    return s;
    } else {
    return '';
    }
}
function collapseAll(){
$('#tg').treegrid('collapseAll');
}
function expandAll(){
$('#tg').treegrid('expandAll');
}
function expandTo(){
$('#tg').treegrid('expandTo',21).treegrid('select',21);
}
</script>
</head>
<body style="margin: 5px;">
<table id="dg" title="用户信息" class="easyui-datagrid" fitColumns="true"
pagination="true" rownumbers="true" url="user/list.do" fit="false"
toolbar="#tb">
<thead>
<tr>
<th field="cb" checkbox="true"></th>
<th field="uid" width="100">编号</th>
<th field="truename" width="60">真名</th>
<th field="loginname" width="80">账号</th>
<th field="email" width="80">邮箱</th>
<th field="activationCode" width="200">**码</th>
<th data-options="field:'progress',width:120,formatter:formatProgress">进度</th>
</tr>
</thead>
</table>


<div id="tb">
<div>
<a href="javascript:openGradeAddDialog()" class="easyui-linkbutton"
iconCls="icon-add" plain="true">添加</a> <a
href="javascript:openGradeModifyDialog()" class="easyui-linkbutton"
iconCls="icon-edit" plain="true">修改</a> <a
href="javascript:deleteGrade()" class="easyui-linkbutton"
iconCls="icon-remove" plain="true">删除</a>
</div>
<div>
&nbsp;班级名称:&nbsp;<input type="text" name="s_truename" id=s_truename /><a
href="javascript:searchGrade()" class="easyui-linkbutton"
iconCls="icon-search" plain="true">搜索</a>
</div>
</div>


<div id="dlg" class="easyui-dialog"
style="width: 900px; height: 600px; padding: 10px 20px" closed="true"
buttons="#dlg-buttons">
<form id="fm" method="post">
<table>
<tr>
<td>账号:</td>
<td><input type="text" name="loginname" id="loginname"
class="easyui-validatebox" required="true"
validType="minLength[3]" missingMessage="不能为空" /></td>
</tr>


<tr>
<td>密码:</td>
<td><input type="text" name="loginpass" id="loginpass"
class="easyui-validatebox" required="true"
validType="minLength[3]" missingMessage="不能为空" /></td>
</tr>
<tr>
<td>邮箱:</td>
<td><input type="text" name="email" id="email"
class="easyui-validatebox" required="true" validType="email"
invalidMessage="请填写正确的邮箱" /></td>
</tr>

<tr>
<td>状态:</td>
<td><select class="easyui-combobox" id="status" name="status"
editable="false" required="true" panelHeight="auto"
style="width: 155px">
<option value="">请选择...</option>
<option value="1">启用</option>
<option value="0">禁用</option>
</select></td>
</tr>


<tr>
<td>角色:</td>
<td><input class="easyui-combobox" id="roleid" name="roleid"
data-options="panelHeight:'auto',editable:false,valueField:'id',textField:'name',url:'user/comboList.do'" />
</td>
</tr>

<tr>
<td>电话:</td>
<td><input type="text" name="tel" id="tel"
class="easyui-numberbox" required="true" validType="number"
missingMessage="请输入数字" /></td>
</tr>





<tr>
<td>真实姓名:</td>
<td><input type="text" name="truename" id="truename"
class="easyui-validatebox" required="true"
missingMessage="真实姓名不能为空" /></td>
</tr>



<tr>
<td>进度:</td>
<td><input type="text" name="progress" id="progress"
class="easyui-numberbox" required="true" validType="number"
missingMessage="请输入数字"  /></td>
</tr>






<tr>
<td valign="top">地址描述:</td>
<td><textarea class="easyui-kindeditor"   name="address" id="address" style="width: 200px; height: 200px;"></textarea></td>
</tr>


</table>
</form>
</div>




<div id="dlg-buttons">
<a href="javascript:save()" class="easyui-linkbutton"
iconCls="icon-ok">保存</a> <a href="javascript:closeGradeDialog()"
class="easyui-linkbutton" iconCls="icon-cancel">关闭</a>
</div>




















<script type="text/javascript">
/**/
KindEditor.ready(function(K) {
var content = K.create(
'textarea[name="address"]',
{
uploadJson : 'ftp/fileUpload',  //指定上传文件的服务器端程序。
fileManagerJson : 'file/fileManager',  //指定浏览远程图片的服务器端程序。
allowFileManager : true,   //true时显示浏览远程服务器按钮。
            allowImageUpload : true,  //true时显示图片上传按钮。
            autoHeightMode : true, 
            resizeType: 1,
afterCreate : function() {this.loadPlugin('autoheight');},  
        afterBlur : function(){ this.sync(); }  //Kindeditor下获取文本框信息  失去焦点的时候执行
});
});
</script>
























</body>

</html>








-----------------下面是java代码----------------------------

package com.dt.controller;


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Random;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import com.alibaba.fastjson.JSONObject;


@Controller
@RequestMapping("file")
public class FileController {


// windows
private String PATH_LINE = "\\";
// linux
// private String PATH_LINE = "/";


@SuppressWarnings("unchecked")
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
@ResponseBody
public void fileUpload(HttpServletRequest request, HttpServletResponse response,
@RequestParam("imgFile") MultipartFile[] imgFile) {
try {
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();


// 文件保存本地目录路径
String savePath = request.getSession().getServletContext().getRealPath(PATH_LINE) + "kindeditor" + PATH_LINE
+ "attached" + PATH_LINE;
System.out.println("本地路径:" + savePath);
// 文件保存目录URL
String saveUrl = request.getContextPath() + PATH_LINE + "kindeditor" + PATH_LINE + "attached" + PATH_LINE;


System.out.println("文本url:" + saveUrl);


if (!ServletFileUpload.isMultipartContent(request)) {
out.print(getError("请选择文件。"));
out.close();
return;
}
// 检查目录
File uploadDir = new File(savePath);
if (!uploadDir.isDirectory()) {
out.print(getError("上传目录不存在。"));
out.close();
return;
}
// 检查目录写权限
if (!uploadDir.canWrite()) {
out.print(getError("上传目录没有写权限。"));
out.close();
return;
}


String dirName = request.getParameter("dir");
if (dirName == null) {
dirName = "image";
}


// 定义允许上传的文件扩展名
Map<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
extMap.put("flash", "swf,flv");
extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,xml,txt,zip,rar,gz,bz2");


if (!extMap.containsKey(dirName)) {
out.print(getError("目录名不正确。"));
out.close();
return;
}
// 创建文件夹
savePath += dirName + PATH_LINE;
saveUrl += dirName + PATH_LINE;
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}


SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
savePath += ymd + PATH_LINE;
saveUrl += ymd + PATH_LINE;
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}


// 最大文件大小
long maxSize = 1000000;


// 保存文件
for (MultipartFile iFile : imgFile) {
String fileName = iFile.getOriginalFilename();


// 检查文件大小
if (iFile.getSize() > maxSize) {
out.print(getError("上传文件大小超过限制。"));
out.close();
return;
}
// 检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {
// return getError("上传文件扩展名是不允许的扩展名。\n只允许" +
// extMap.get(dirName) + "格式。");
out.print(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
out.close();
return;
}


SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
System.out.println(savePath+newFileName);
try {
File uploadedFile = new File(savePath, newFileName);


// 写入文件
FileUtils.copyInputStreamToFile(iFile.getInputStream(), uploadedFile);
} catch (Exception e) {
out.print(getError("上传文件失败。"));
out.close();
return;
}


JSONObject obj = new JSONObject();
obj.put("error", 0);
obj.put("url", saveUrl + newFileName);
System.out.println("-------最后的路径--------"+saveUrl + newFileName);


out.print(obj.toJSONString());
out.close();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


private Map<String, Object> getError(String errorMsg) {
Map<String, Object> errorMap = new HashMap<String, Object>();
errorMap.put("error", 1);
errorMap.put("message", errorMsg);
return errorMap;
}


/**
* 文件空间

* @param request
*            {@link HttpServletRequest}
* @param response
*            {@link HttpServletResponse}
* @return json
*/
@RequestMapping(value = "/fileManager")
@ResponseBody
public void fileManager(HttpServletRequest request, HttpServletResponse response) {
//System.out.println("获取核心path参数:"+request.getParameter("path"));
try {
// 根目录路径,可以指定绝对路径
String rootPath = request.getSession().getServletContext().getRealPath(PATH_LINE) + "kindeditor" + PATH_LINE
+ "attached" + PATH_LINE;
// 根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
String rootUrl = request.getContextPath() + PATH_LINE + "kindeditor" + PATH_LINE + "attached" + PATH_LINE;
response.setContentType("application/json; charset=UTF-8");
PrintWriter out = response.getWriter();


// 图片扩展名
String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };


String dirName = request.getParameter("dir");
if (dirName != null) {
if (!Arrays.<String> asList(new String[] { "image", "flash", "media", "file" }).contains(dirName)) {
out.print("无效的文件夹。");

out.close();
return;
}
rootPath += dirName + PATH_LINE;
rootUrl += dirName + PATH_LINE;

File saveDirFile = new File(rootPath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
}
// 根据path参数,设置各路径和URL
String path = request.getParameter("path") != null ? request.getParameter("path") : "";

String currentPath = rootPath + path;
String currentUrl = rootUrl + path;
String currentDirPath = path;
String moveupDirPath = "";
if (!"".equals(path)) {
String str = currentDirPath.substring(0, currentDirPath.length() - 1);
moveupDirPath = str.lastIndexOf(PATH_LINE) >= 0 ? str.substring(0, str.lastIndexOf(PATH_LINE) + 1) : "";
}
// 排序形式,name or size or type
String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";
        
// 不允许使用..移动到上一级目录
if (path.indexOf("..") >= 0) {
out.print("访问权限拒绝。");
out.close();
return;
}

/* 最后一个字符不是
if (!"".equals(path) && !path.endsWith(PATH_LINE)) {
out.print("无效的访问参数验证。");
System.out.println("无效的访问参数验证。");
out.close();
return;
}*/

//最后一个字符不是/
System.out.println(path);
if (!"".equals(path) && !path.endsWith("/")) {
out.println("Parameter is not valid.");
return;
}

// 目录不存在或不是目录
File currentPathFile = new File(currentPath);
if (!currentPathFile.isDirectory()) {
out.print("文件夹不存在。");
out.close();
return;
}


// 遍历目录取的文件信息
List<Map<String, Object>> fileList = new ArrayList<Map<String, Object>>();
if (currentPathFile.listFiles() != null) {
for (File file : currentPathFile.listFiles()) {
Hashtable<String, Object> hash = new Hashtable<String, Object>();
String fileName = file.getName();
if (file.isDirectory()) {
hash.put("is_dir", true);
hash.put("has_file", (file.listFiles() != null));
hash.put("filesize", 0L);
hash.put("is_photo", false);
hash.put("filetype", "");
} else if (file.isFile()) {
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
hash.put("is_dir", false);
hash.put("has_file", false);
hash.put("filesize", file.length());
hash.put("is_photo", Arrays.<String> asList(fileTypes).contains(fileExt));
hash.put("filetype", fileExt);
}
hash.put("filename", fileName);
hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
fileList.add(hash);
}
}


if ("size".equals(order)) {
Collections.sort(fileList, new SizeComparator());
} else if ("type".equals(order)) {
Collections.sort(fileList, new TypeComparator());
} else {
Collections.sort(fileList, new NameComparator());
}


JSONObject result = new JSONObject();
result.put("moveup_dir_path", moveupDirPath);
result.put("current_dir_path", currentDirPath);
result.put("current_url", currentUrl);
result.put("total_count", fileList.size());
result.put("file_list", fileList);


out.println(result.toJSONString());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}


private class NameComparator implements Comparator<Map<String, Object>> {
public int compare(Map<String, Object> hashA, Map<String, Object> hashB) {
if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
return -1;
} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
return 1;
} else {
return ((String) hashA.get("filename")).compareTo((String) hashB.get("filename"));
}
}
}


private class SizeComparator implements Comparator<Map<String, Object>> {
public int compare(Map<String, Object> hashA, Map<String, Object> hashB) {
if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
return -1;
} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
return 1;
} else {
if (((Long) hashA.get("filesize")) > ((Long) hashB.get("filesize"))) {
return 1;
} else if (((Long) hashA.get("filesize")) < ((Long) hashB.get("filesize"))) {
return -1;
} else {
return 0;
}
}
}
}


private class TypeComparator implements Comparator<Map<String, Object>> {
public int compare(Map<String, Object> hashA, Map<String, Object> hashB) {
if (((Boolean) hashA.get("is_dir")) && !((Boolean) hashB.get("is_dir"))) {
return -1;
} else if (!((Boolean) hashA.get("is_dir")) && ((Boolean) hashB.get("is_dir"))) {
return 1;
} else {
return ((String) hashA.get("filetype")).compareTo((String) hashB.get("filetype"));
}
}
}


}

-----------------------------------------------------------------------------------

package com.dt.controller;


import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;


import com.alibaba.fastjson.JSONObject;
import com.dt.util.FtpUtil;


@Controller
@RequestMapping("ftp")
public class FtpController {
@RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
@ResponseBody
public void fileUpload(HttpServletRequest request, HttpServletResponse response,
@RequestParam("imgFile") MultipartFile imgFile) throws IOException {
JSONObject obj = new JSONObject();
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();


System.out.println("---------");


try {
// 上传文件功能实现
// 判断文件是否为空
if (imgFile.isEmpty()) {


}


// 上传文件以日期为单位分开存放,可以提高图片的查询速度
String filePath = "/" + new SimpleDateFormat("yyyy").format(new Date()) + "/"
+ new SimpleDateFormat("MM").format(new Date()) + "/"
+ new SimpleDateFormat("dd").format(new Date());


// 取原始文件名
// String originalFilename = imgFile.getOriginalFilename();
String new_filename = genImageName() + ".jpg";


// 转存文件,上传到ftp服务器
FtpUtil.uploadFile("192.168.1.110", 21, "test", "123456", "", filePath, new_filename,
imgFile.getInputStream());
String pp = "http://192.168.1.110/img" + filePath + "/" + new_filename;
System.out.println("******pp******" + pp);
obj.put("error", 0);
obj.put("url", pp);


} catch (Exception e) {
e.printStackTrace();
}


out.print(obj.toJSONString());
out.close();


}
/*

* FTPClient ftpClient = new FTPClient();
* ftpClient.connect("192.168.25.200"); ftpClient.login("ftpuser",
* "ftpuser"); FileInputStream inputStream = new FileInputStream(new
* File("D:\\Documents\\Pictures\\pics\\21.jpg"));
* ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
* ftpClient.storeFile("123.jpg", inputStream); inputStream.close();

* ftpClient.logout();

*/


/**
* 图片名生成
*/
public static String genImageName() {
// 取当前时间的长整形值包含毫秒
long millis = System.currentTimeMillis();
// long millis = System.nanoTime();
// 加上三位随机数
Random random = new Random();
int end3 = random.nextInt(999);
// 如果不足三位前面补0
String str = millis + String.format("%03d", end3);


return str;
}


}

----------------------------------------------------------------------------------------------------



package com.dt.util;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;


/**
 * ftp上传下载工具类
 * <p>Title: FtpUtil</p>
 * <p>Description: </p>
 * <p>Company: www.itcast.com</p> 
 * @author 入云龙
 * @date 2015年7月29日下午8:11:51
 * @version 1.0
 */
public class FtpUtil {


/** 
* Description: 向FTP服务器上传文件 
* @param host FTP服务器hostname 
* @param port FTP服务器端口 
* @param username FTP登录账号 
* @param password FTP登录密码 
* @param basePath FTP服务器基础目录
* @param filePath FTP服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basePath+filePath
* @param filename 上传到FTP服务器上的文件名 
* @param input 输入流 
* @return 成功返回true,否则返回false 
*/  
public static boolean uploadFile(String host, int port, String username, String password, String basePath,
String filePath, String filename, InputStream input) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);// 连接FTP服务器
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
//切换到上传目录
if (!ftp.changeWorkingDirectory(basePath+filePath)) {
//如果目录不存在创建目录
String[] dirs = filePath.split("/");
String tempPath = basePath;
for (String dir : dirs) {
if (null == dir || "".equals(dir)) continue;
tempPath += "/" + dir;
if (!ftp.changeWorkingDirectory(tempPath)) {
if (!ftp.makeDirectory(tempPath)) {
return result;
} else {
ftp.changeWorkingDirectory(tempPath);
}
}
}
}
//设置上传文件的类型为二进制类型
ftp.setFileType(FTP.BINARY_FILE_TYPE);
//上传文件
if (!ftp.storeFile(filename, input)) {
return result;
}
input.close();
ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}

/** 
* Description: 从FTP服务器下载文件 
* @param host FTP服务器hostname 
* @param port FTP服务器端口 
* @param username FTP登录账号 
* @param password FTP登录密码 
* @param remotePath FTP服务器上的相对路径 
* @param fileName 要下载的文件名 
* @param localPath 下载后保存到本地的路径 
* @return 
*/  
public static boolean downloadFile(String host, int port, String username, String password, String remotePath,
String fileName, String localPath) {
boolean result = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(host, port);
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName());


OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), is);
is.close();
}
}


ftp.logout();
result = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return result;
}

public static void main(String[] args) {
try {  
       FileInputStream in=new FileInputStream(new File("D:\\temp\\image\\gaigeming.jpg"));  
       boolean flag = uploadFile("192.168.25.133", 21, "ftpuser", "ftpuser", "/home/ftpuser/www/images","/2015/01/21", "gaigeming.jpg", in);  
       System.out.println(flag);  
   } catch (FileNotFoundException e) {  
       e.printStackTrace();  
   }  
}
}