资料扫描管理系统文件上传模块(MVC1)
1、使用的技术jsp、servlet、swfupload、jquery
2、MVC模式
这个模块使用的是:jsp直接请求到servlet中,通过swfupload实现图片的批量上传。
3、工程的组织结构
4、重要代码
SaveFileServlet
package com.asiainfo.crm.infomanage.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.asiainfo.crm.infomanage.util.FtpUtil;
import com.asiainfo.crm.infomanage.util.SeqUtils;
import com.jspsmart.upload.Request;
public class SaveFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("GBK");
FtpUtil ftpUtil = new FtpUtil();
try {
ftpUtil.initialize(this.getServletConfig(), request, response);
Request request2=ftpUtil.getRequest();
/*String test=request2.getParameter("test")!=null?request2.getParameter("test"):"";
System.out.println("=="+test);*/
String[] temp=SeqUtils.hostInfo;
String[] hostInfo=new String[6];
if(temp[0]!=null&&!"".equals(temp[0])){
hostInfo=temp;
}else{
hostInfo = SeqUtils.getHostInfo();
}
String imageid=ftpUtil.batUploadFile(hostInfo[0], Integer.valueOf(hostInfo[1]).intValue(), hostInfo[2], hostInfo[3],"",request);
response.getWriter().print(imageid);
} catch (Exception e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
ImageUtils
package com.asiainfo.crm.infomanage.util;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import javax.imageio.ImageIO;
import sun.awt.image.ToolkitImage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.jimi.core.Jimi;
import com.sun.jimi.core.JimiReader;
public class ImageUtils {
public ImageUtils() {
}
/** *//**
* 把图片印刷到图片上
*
* @param pressImg --
* 水印文件
* @param targetImg --
* 目标文件
* @param x
* --x坐标
* @param y
* --y坐标
* @param alpha
* --透明度
*/
public final static BufferedImage pressImage(boolean istif,File pressImg, InputStream targetImg,
int x, int y,float alpha) {
List img_list = new ArrayList();
int img_type = 1;
int wideth =0;
int height =0;
try {
//目标文件
float Alpha=alpha;
BufferedImage image=null;
Image src=null;
if(istif){
JimiReader reader = Jimi.createJimiReader(targetImg);
Enumeration e = reader.getImageEnumeration();
BufferedImage b_img=null;
while (e.hasMoreElements()) {
ToolkitImage t_img = (ToolkitImage) e.nextElement();
b_img = t_img.getBufferedImage();
if (b_img == null) {
img_type = 2;
break;
}
img_list.add(b_img);
}
if (img_list.size() < 1) {
return null;
}
if (img_list.size() > 1) {
src = CombImage(img_list);
} else {
src = (BufferedImage) img_list.get(0);
}
}else{
src = ImageIO.read(targetImg);
}
wideth=src.getWidth(null);
height= src.getHeight(null);
image = new BufferedImage(wideth, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
// if(istif){
g.drawImage(src, 0, 0, wideth, height, null);
//}else{
//g.drawImage(src, 0, 0, wideth, height, null);
//}
//水印文件
File _filebiao =pressImg;
Image src_biao = ImageIO.read(_filebiao);
int wideth_biao = src_biao.getWidth(null);
int height_biao = src_biao.getHeight(null);
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
Alpha));
g.drawImage(src_biao, (wideth - wideth_biao) / 2,
(height - height_biao) / 2, wideth_biao, height_biao, null);
//水印文件结束
g.dispose();
targetImg.close();
//ImageIO.write(image, "jpg", new FileOutputStream(new File("d:/t.jpg")));
return image;
/* FileOutputStream out = new FileOutputStream();
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();*/
//FileInputStream fileInputStream=new FileInputStream(targetImg);
// FileOutputStream out = new FileOutputStream(targetImg);
// JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
//encoder.encode(image);
// out.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/** *//**
* 打印文字水印图片
*
* @param pressText
* --文字
* @param targetImg --
* 目标图片
* @param fontName --
* 字体名
* @param fontStyle --
* 字体样式
* @param color --
* 字体颜色
* @param fontSize --
* 字体大小
* @param x --
* 偏移量
* @param y
*/
public static void pressText(String pressText, String targetImg,
String fontName, int fontStyle, int color, int fontSize, int x,
int y,float alpha) {
try {
float Alpha=alpha;
File _file = new File(targetImg);
Image src = ImageIO.read(_file);
int wideth = src.getWidth(null);
int height = src.getHeight(null);
BufferedImage image = new BufferedImage(wideth, height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.drawImage(src, 0, 0, wideth, height, null);
g.setColor(Color.RED);
g.setFont(new Font(fontName, fontStyle, fontSize));
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,
Alpha));
g.drawString(pressText, wideth - fontSize - x, height - fontSize
/ 2 - y);
g.dispose();
FileOutputStream out = new FileOutputStream(targetImg);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) {
// pressImage("d:\\unicomlog.jpg", "d:\\bb.jpg", 100, 200,0.1f);
// pressImage("d:\\bb.jpg", "d:\\aa.jpg", 200, 200,0.6f);
/* for(int i=0;i<500;i++){
pressImage("d:\\bb.jpg", "d:\\cc.jpg", i+100, i+100,0.6f);
i=i*10;
System.out.println(i);
}*/
// pressText("谭建平哈哈", "d:\\aa.jpg","隶书",36,36,36, 300, 400,0.5f);
System.out.print("添加成功");
}
public static BufferedImage CombImage(List img_list) {
BufferedImage sample_img = (BufferedImage) img_list.get(0);
int width = sample_img.getWidth();
int height = sample_img.getHeight();
int img_type = sample_img.getType();
if (img_type == BufferedImage.TYPE_CUSTOM) {
img_type = BufferedImage.TYPE_INT_RGB;
}
BufferedImage ret_img = new BufferedImage(width, height
* img_list.size(), img_type);
Graphics2D g = (Graphics2D) ret_img.getGraphics();
g.setBackground(Color.WHITE);
g.setColor(Color.WHITE);
g.fillRect(0, 0, width, height * img_list.size());
int h_pos = 0;
for (int i = 0; i < img_list.size(); i++) {
BufferedImage img = (BufferedImage) img_list.get(i);
g.drawImage(img, 0, h_pos, null);
h_pos += img.getHeight();
}
return ret_img;
}
}
fileutil_1.jsp
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@page import="com.asiainfo.crm.infomanage.util.SeqUtils"%>
<html>
<head>
<title>文件上传</title>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<link rel="stylesheet" href="../css/sytle_public_skin.css" type="text/css"></link>
<script type="text/javascript" src="../js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="../swfupload/swfupload.js"></script>
<script type="text/javascript" src="../swfupload/handler.js"></script>
<script type="text/javascript">
var end;
var swfu;
var seqs;
window.onload = function () {
swfu = new SWFUpload({
button_image_url : "../swfupload/upload.png",//指向图片按钮的位置
button_placeholder_id : "spanButtonPlaceholder",//该按钮的ID名字
button_width: 68,//按钮的宽度
button_height: 21,//按钮的高度
//button_text : "选择文件",//按钮中的文字
flash_url : "../swfupload/swfupload.swf",//指向FLASH文件的位置
upload_url: "<%=basePath%>servlet/SaveFileServlet",//指向web项目下的名为upload的action
upload_complete_handler:uploadComplete,//用于处理文件上传结束的事件
file_dialog_complete_handler : fileDialogComplete,//用于处理选择文件后触发的事件
file_queued_handler : fileQueued,//用于处理选择文件后触发的事件
upload_error_handler:uploadError,//用于处理上传失败触发的事件
upload_success_handler:uploadSuccess,//用于处理上传成功触发的事件
file_types : "*.jpg;*.gif;*.bmp", //文件类型
file_dialog_start_handler: fileDialogStart,
file_size_limit : "1 MB", //上传文件体积上限,单位MB
file_queue_error_handler : fileQueueError, //文件选择失败后触发事件(类型不对、大小不对等等)
//添加照片的按钮设置
button_text_left_padding: -1,
button_text_top_padding: -1,
//button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
button_cursor: SWFUpload.CURSOR.HAND, //鼠标手型
queue_complete_handler : queueComplete, //队列上传完成
//upload_complete_handler : uploadComplete //完成1
upload_progress_handler : uploadProgress
// allowDuplicates : true //不允许选择重复文件
});
//document.getElementById(swfu.customSettings.uploadButtonId).disabled = true;
};
</script>
<script type="text/javascript">
<%
String operatorid=request.getParameter("operatorid")!=null?request.getParameter("operatorid"):"";
if(!"".equals(operatorid)){
request.getSession().setAttribute("operatorid",operatorid);
}
String soperatorid=request.getSession().getAttribute("operatorid")!=null?(String)request.getSession().getAttribute("operatorid"):"";
if("".equals(soperatorid)){
response.sendRedirect("http://www.cnblogs.com/../index.jsp");
}
//String dayupload=SeqUtils.getDayUpload();
%>
$(document).ready(function (){
<%
String isok=request.getParameter("isok")!=null?request.getParameter("isok"):"";
String check=request.getParameter("check")!=null?request.getParameter("check"):"";
if("true".equals(check)){
if("ok".equals(isok)){
%>
alert("上传成功");
<%
}else{
%>
alert("上传失败");
<%
}
}
%>
});
function searchFiles(){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var f = fso.GetFolder(document.all.fixfolder.value);
var fc = new Enumerator(f.files);
var s = "";
tcount=0;
seqs="";
//以下内容是显示文件名
// alert(11);
$("#fileTable").children().remove();
var i=0;
//var n=0;
for (; !fc.atEnd(); fc.moveNext())
{
var baseName=ShowBaseName(fc.item());
var extensinName= ShowExtensionName(fc.item());
var extensinNameLower=extensinName.toLowerCase();
if(extensinNameLower=="jpg"||extensinNameLower=="bmp"||extensinNameLower=="gif"){
filename=baseName+"."+extensinName;
var allfilename=fc.item();
i++;
var temp="<tr id=\"tr"+baseName+"\" style=\"display: none;\" ><form onsubmit=\"return false\" id=\"form"+baseName+"\"><td nowrap=\"nowrap\"><input type=\"hidden\" name=\"imgName\" id=\"imgName"+baseName+"\"><input type=\"hidden\" name=\"imgPath\" id=\"imgPath"+baseName+"\"><input type=\"hidden\" name=\"imgId\" id=\"imgId"+baseName+"\"><input type=\"hidden\" name=\"formerName\" id=\"formerName"+baseName+"\"><input class=\"classbarc"+i+"\" id=\""+baseName+"\" title=\""+allfilename+"\" type=\"checkbox\" name=\"filecheck\" onclick=\"broswimage('"+allfilename+"','"+baseName+"');\"></td><td nowrap=\"nowrap\"><input type=\"text\" class=\"classbari"+i+"\" onKeyDown=\"setnetbar('"+baseName+"','"+i+"');\" id=\"txm"+baseName+"\" name=\"barcode\" maxlength=\"12\" onkeypress=\"return event.keyCode>=48&&event.keyCode<=57||event.keyCode==46\" onpaste=\"return !clipboardData.getData('text').match(/\D/)\" ondragenter=\"return false\" size=\"15\"><td nowrap=\"nowrap\"><span class=\"rulie\" id=\"s"+baseName+"\">未选文件<span><td nowrap=\"nowrap\" id=\"fil"+baseName+"\"> "+filename+"</td></form></tr>";
$("#fileTable").append(temp);
}
}
end=i;
if(i>0){
$("#mysp").show();
}
//$("#fileTable").hide();
//以下内容是显示目录名
/**
fk = new Enumerator(f.SubFolders);
for (; !fk.atEnd(); fk.moveNext())
{
document.write(fk.item()+"<br>");
}
*/
}
//获得文件名
function ShowBaseName(filespec)
{
var fso, s = "";
fso = new ActiveXObject("Scripting.FileSystemObject");
s += fso.GetBaseName(filespec);
return(s);
}
//获得扩展名
function ShowExtensionName(filespec)
{
var fso, s = "";
fso = new ActiveXObject("Scripting.FileSystemObject");
s += fso.GetExtensionName(filespec);
return(s);
}
//path 要显示值的对象id
function browseFolder(path) {
try {
var Message = "\u8bf7\u9009\u62e9\u6587\u4ef6\u5939"; //选择框提示信息
var Shell = new ActiveXObject("Shell.Application");
var Folder = Shell.BrowseForFolder(0, Message, 64, 17);//起始目录为:我的电脑
//var Folder = Shell.BrowseForFolder(0,Message,0); //起始目录为:桌面
if (Folder != null) {
Folder = Folder.items(); // 返回 FolderItems 对象
Folder = Folder.item(); // 返回 Folderitem 对象
Folder = Folder.Path; // 返回路径
if (Folder.charAt(Folder.length - 1) != "\\") {
Folder = Folder + "\\";
}
document.getElementById("fixfolder").value = Folder;
return Folder;
}
}
catch (e) {
alert(e.message);
}
}
function filesubmit(){
//alert("准备上传总数="+tcount);
//return false;
fileformsubmit();
}
function setnetbar(baseName,bi){
bbi=parseInt(bi)+1;
if(event.keyCode==13){
$('.classbarc'+bbi).attr("checked",true);
if(bbi<=end){
var bname=$('.classbarc'+bbi).attr("id");
broswimage("",bname);
$('.classbari'+bbi).focus();
}
}
}
</script>
</head>
FtpUtil
package com.asiainfo.crm.infomanage.util;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import sun.net.TelnetInputStream;
import com.asiainfo.core.util.CommUtil;
import com.asiainfo.crm.infomanage.model.BmsImgInfo;
import com.asiainfo.crm.infomanage.model.ShMatOperateLog;
import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
public class FtpUtil {
private static final Log logger = LogFactory.getLog(FtpUtil.class);
private SmartUpload mySmartUpload = new SmartUpload();
private Request request = null;
public FtpUtil() {
}
/**
* 初始化验证上传文件大小
* @param pagecontext
* @throws Exception
*/
public void initialize(ServletConfig servletConfig,HttpServletRequest srequest,HttpServletResponse response) throws Exception {
long maxsize =0; // 设置每个上传文件的大小MB
if(SeqUtils.maxFileSize==0){
maxsize = SeqUtils.maxFileSize(); // 设置每个上传文件的大小MB
}else{
maxsize=SeqUtils.maxFileSize;
}
try {
mySmartUpload.initialize(servletConfig,srequest,response);
mySmartUpload.setMaxFileSize(maxsize); // 限制上传文件的大小
mySmartUpload.upload();
request = mySmartUpload.getRequest();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("最大只能上传"+maxsize);
}
}
/**
* Description: 向FTP服务器上传文件
* @Version1.0
* @param url FTP服务器hostname
* @param port FTP服务器端口
* @param userName FTP登录账号
* @param passWord FTP登录密码
* @param filePath FTP服务器保存目录
* @param fileName 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public boolean uploadFile(String url, int port, String userName,
String passWord, String fileName, String serviceFilePath)throws Exception {
boolean success = false;
FTPClient ftpClient = new FTPClient();
BufferedInputStream buffIn = null;
logger.info("上传文件数:" + mySmartUpload.getFiles().getCount());
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
//myFile.get
TelnetInputStream ftpIn = null;
try {
ftpIn = new TelnetInputStream(myFile.getStream(), true);
} catch (ServletException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SmartUploadException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
if (connectToServer(ftpClient, url, port, userName, passWord) == false) {
return success;
}
//设置上传目录,如果目录不存在新建目录
checkPathExist(ftpClient, serviceFilePath);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
//设置文件类型(二进制)
setFileType(ftpClient, FTPClient.BINARY_FILE_TYPE);
//文件保存
buffIn = new BufferedInputStream(ftpIn);
ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
logger.info("文件正在上传。。。");
ftpClient.storeFile(fileName, buffIn);
success = true;
logger.info("文件上传成功");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("连接FTP客户端出错!", e);
} finally {
IOUtils.closeQuietly(buffIn);
if (ftpClient.isConnected()) {
try {
closeConnect(ftpClient);
} catch (Exception ioe) {
ioe.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", ioe);
}
}
}
return success;
}
/**
*
* Description: 向FTP服务器上传文件
* @Version1.0
* @param url FTP服务器hostname
* @param port FTP服务器端口
* @param userName FTP登录账号
* @param passWord FTP登录密码
* @param filePath FTP服务器保存目录
* @param fileName 上传到FTP服务器上的文件名
* @param input 输入流
* @return 成功返回true,否则返回false
*/
public String batUploadFile(String url, int port, String userName,
String passWord, String operatorName,HttpServletRequest srequest)throws Exception {
String success = "";
FTPClient ftpClient = new FTPClient();
if (connectToServer(ftpClient, url, port, userName, passWord) == false) {
return success;
}
BufferedInputStream buffIn = null;
//String yyyy = "/"+SeqUtils.getDateString("yyyy");
logger.info("上传文件数:" + mySmartUpload.getFiles().getCount());
String operatorid=request.getParameter("operatorid")!=null?request.getParameter("operatorid"):"";
//System.out.println("====fileutil="+operatorid);
try {
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
//设置文件类型(二进制)
setFileType(ftpClient, FTPClient.BINARY_FILE_TYPE);
String yyyy = "/"+SeqUtils.getDateString("yyyy");
String yyyyMMdd = SeqUtils.getDateString("yyyyMMdd");
String path=yyyy+"/barcode/"+yyyyMMdd+"/";
//String[] txmValues=request.getParameterValues("txm");
//String[] lbValues=request.getParameterValues("lb");
String imageid="";
String basename="";
String imagename="";
String isnull="no";
for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) {
TelnetInputStream ftpIn = null;
com.jspsmart.upload.File myFile = mySmartUpload.getFiles()
.getFile(i);
String fileName = myFile.getFileName();
basename = fileName.substring(0, fileName
.lastIndexOf("."));
String barcode=request.getParameter(basename)!=null?request.getParameter(basename):"";
if("".equals(barcode)){
logger.info("没有文件上传!");
isnull="ok";
break;
}
System.out.println(barcode+"=barcode");
String extensionName=fileName.substring(fileName.lastIndexOf("."),fileName.length());
imageid=SeqUtils.genNextRecordSequenceId();
BmsImgInfo bmsImgInfo=new BmsImgInfo();
bmsImgInfo.setImgId("0"+imageid);//唯一ID
bmsImgInfo.setBarcode(barcode);//条码
bmsImgInfo.setImgType("O");//图片类型
bmsImgInfo.setImgPath(path);//图片路径
bmsImgInfo.setImgName(bmsImgInfo.getImgId()+extensionName);//图片名称
bmsImgInfo.setOperatorId(operatorid);//上传操作员
bmsImgInfo.setCreateDate(new Date());//上传时间
bmsImgInfo.setActiveDate(new Date());//生效时间
bmsImgInfo.setFormerName(fileName);//原文件名
bmsImgInfo.setStatus("1");
imagename=bmsImgInfo.getImgName();
//设置上传目录,如果目录不存在新建目录
if(i==0){
checkPathExist(ftpClient,path);
}
//获取图片上传流,文件保存
ftpIn = new TelnetInputStream(myFile
.getStream(), true);
buffIn = new BufferedInputStream(ftpIn);
String syfile = srequest.getSession().getServletContext().getRealPath(
"/")
+ "/sy/unicomlog.jpg";
syfile = syfile.replace("\\", "/");
System.out.println(syfile);
File syprefile = new File(syfile);
BufferedImage ss=null;
boolean istiff=false;
if(extensionName.equals(".tif")){
istiff=true;
}
ss=ImageUtils.pressImage(istiff,syprefile, buffIn, 100, 200, 0.1f);
ByteArrayOutputStream bao=new ByteArrayOutputStream();
//if(extensionName.equals(".tif")){
// ImageIO.write(ss, "tiff",bao);
// }else{
ImageIO.write(ss, "jpg",bao); //将图片写到这个流中
//}
byte[] bytes= bao.toByteArray();
ByteArrayInputStream bis=new ByteArrayInputStream(bytes);
ftpClient.storeFile(
bmsImgInfo.getImgName(), bis);
logger.info("文件" + myFile.getFileName() + "正在上传,请稍等!");
bao.close();
bis.close();
saveImageInfo(bmsImgInfo);//保存图片信息
ShMatOperateLog shMatOperateLog=new ShMatOperateLog();
shMatOperateLog.setOperatorId(operatorid);
shMatOperateLog.setBarcode(bmsImgInfo.getBarcode());
shMatOperateLog.setOperateType("3");//资料交接
saveShMatOperateLog(shMatOperateLog);
updateShMatOperate(bmsImgInfo.getBarcode());
}
logger.info("文件上传成功!");
imageid="O"+imageid;
success = imageid+","+basename+","+path+","+imagename+","+isnull;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Exception!", e);
} finally {
IOUtils.closeQuietly(buffIn);
if (ftpClient.isConnected()) {
try {
closeConnect(ftpClient);
} catch (Exception ioe) {
ioe.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", ioe);
}
}
}
return success;
}
/**
* Description: 向FTP服务器上传文件
* @Version1.0
* @param url FTP服务器hostname
* @param port FTP服务器端口
* @param userName FTP登录账号
* @param passWord FTP登录密码
* @param remotePath FTP服务器保存目录
* @param remoteFileName 下载的文件名
* @param localPath 下载到本地的路径
* @return 成功返回true,否则返回false
*/
public boolean downFile(String url, int port, String userName,
String passWord, String remotePath, String remoteFileName,
String localPath)throws Exception {
boolean success = false;
FTPClient ftpClient = new FTPClient();
OutputStream fos = null;
try {
if (connectToServer(ftpClient, url, port, userName, passWord) == false) {
return success;
}
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("GBK");
//设置文件类型(二进制)
setFileType(ftpClient, FTPClient.BINARY_FILE_TYPE);
//本地文件夹
File dirFile = new File(localPath);
if (!(dirFile.exists()) && !(dirFile.isDirectory())) {
boolean creadok = dirFile.mkdirs();
if (creadok) {
logger.info(localPath + "创建文件夹成功! ");
} else {
logger.info(localPath + "创建文件夹失败! ");
}
}
logger.info("服务器上文件地址" + remotePath + remoteFileName);
if (remotePath.startsWith("/") && remotePath.endsWith("/")) {
//更换目录到指定目录
String path[] = remotePath.split("\\/");
for(int w=0;w<path.length;w++){
ftpClient.changeWorkingDirectory(path[w]);
}
FTPFile[] files = ftpClient.listFiles();
for(int x=0;x<files.length;x++){
FTPFile file=files[x];
if (file.getName().equals(remoteFileName)) {
File localFile = new File(localPath + "/"
+ "bssPhotoCopy.jpg");
//本地保存地址
logger.info("本地保存地址" + localPath + "/"
+ "bssPhotoCopy.jpg");
fos = new FileOutputStream(localFile, true);
logger.info("正在下载文件。。。");
ftpClient.appendFileStream(remotePath + remoteFileName);
ftpClient.retrieveFileStream(remotePath
+ remoteFileName);
ftpClient.retrieveFile(file.getName(), fos);
ftpClient.getBufferSize();
}
}
}
success = true;
logger.info("文件下载成功");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("FTP客户端出错!", e);
} finally {
IOUtils.closeQuietly(fos);
if (ftpClient.isConnected()) {
try {
closeConnect(ftpClient);
} catch (Exception ioe) {
ioe.printStackTrace();
throw new RuntimeException("关闭FTP连接发生异常!", ioe);
}
}
}
return success;
}
/**
* 查找指定目录是否存在
* @param String filePath 要查找的目录
* @return boolean:存在:true,不存在:false
* @throws IOException
*/
private static void checkPathExist(FTPClient ftpClient,
String serviceFilePath) throws IOException {
try {
if (!ftpClient.changeWorkingDirectory(serviceFilePath)) {
//对远程目录的处理
String remoteFileName = serviceFilePath;
if (serviceFilePath.indexOf("/")>=0) {
remoteFileName = serviceFilePath.substring(serviceFilePath
.lastIndexOf("/") + 1);
String directory = serviceFilePath.substring(0,
serviceFilePath.lastIndexOf("/") + 1);
if (!directory.equalsIgnoreCase("/")
&& !ftpClient.changeWorkingDirectory(directory)) {
//如果远程目录不存在,则递归创建远程服务器目录
int start = 0;
int end = 0;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
while (true) {
String subDirectory = serviceFilePath.substring(
start, end);
if (!ftpClient.changeWorkingDirectory(subDirectory)) {
if (ftpClient.makeDirectory(subDirectory)) {
ftpClient
.changeWorkingDirectory(subDirectory);
logger.info("创建:" + subDirectory + "路径成功!");
} else {
logger.info("创建目录失败");
}
}
start = end + 1;
end = directory.indexOf("/", start);
//检查所有目录是否创建完毕
if (end <= start) {
break;
}
}
}
}
}
logger.info("创建:" + serviceFilePath + "路径成功!");
} catch (Exception e) {
e.printStackTrace();
}
}