1.本地文件上传到eclipse
1)处理图片上传的类
package com.gy.apply.admin.platform.contract.controller;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.gy.common.attach.GYFTPClientImpl;
import com.gy.common.attach.GYFtpClient;
import com.gy.common.controller.ExceptionController;
import com.gy.apply.admin.platform.contract.controller.ScaleImage;
/**
* Simple to Introduction
*
* @category 图片上传
* @projectName person-web
* @package com.gy.person.controller.FileUploadController.java
* @className FileUploadController
* @description 实名认证图片上传
* @author zhangnn
* @createDate 2014-9-1 下午12:29:15
* @updateUser zhangnn
* @updateDate 2014-9-1 下午12:29:15
* @updateRemark 说明本次修改内容
* @version v0.0.1
*/
@Controller
@RequestMapping("/file")
public class FileUploadController extends ExceptionController {
@Override
protected ModelAndView doResolveException(HttpServletRequest request,
HttpServletResponse response, Exception ex) {
return null;
}
/**
* 这里用的是MultipartFile[] myfiles参数,所以前台就要用<input type="file"
* name="myfiles"/>
* 上传文件完毕后返回给前台[0`filepath],0表示上传成功(后跟上传后的文件路径),1表示失败(后跟失败描述)
*/
@RequestMapping(value = "/fileUpload")
public String addUser(@RequestParam("customId") String customId,@RequestParam("picName") String picName,
@RequestParam MultipartFile[] myfiles, HttpServletRequest request,
HttpServletResponse response) throws IOException {
// 可以在上传文件的同时接收其它参数
logger.info("收到用户的文件上传请求");
logger.info("#####################" + picName);
InetAddress addr = InetAddress.getLocalHost();
String ip = addr.getHostAddress().toString();//获得本机IP
// 如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
// 这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断/upload是否存在,不存在会自动创建
String realPath = request.getSession().getServletContext()
.getRealPath("/upload");
// 设置响应给前台内容的数据格式
response.setContentType("text/plain; charset=UTF-8");
// 设置响应给前台内容的PrintWriter对象
PrintWriter out = response.getWriter();
// 上传文件的原名(即上传前的文件名字)
String originalFilename = null;
// 如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
// 如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且要指定@RequestParam注解
// 上传多个文件时,前台表单中的所有<input
// type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取
for (MultipartFile myfile : myfiles) {
if (myfile.isEmpty()) {
out.print("1`请选择文件后上传");
out.flush();
return null;
} else {
String myfileName = myfile.getOriginalFilename().trim();
originalFilename = customId +System.currentTimeMillis()+picName
+ myfileName.substring(myfileName.lastIndexOf("."));
logger.info("文件原名: " + originalFilename);
logger.info("文件名称: " + myfile.getName());
logger.info("文件长度: " + myfile.getSize());
logger.info("文件类型: " + myfile.getContentType());
if (myfile.getSize() > 1000000) {
out.print("3`文件过大");
out.flush();
return null;
} else {
try {
// 这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
// 此处也可以使用Spring提供的MultipartFile.transferTo(File
// dest)方法实现文件
FileUtils.copyInputStreamToFile(
myfile.getInputStream(), new File(realPath,
originalFilename.trim()));
//判断上传的文件是不是图片,如果是,就生成缩略图
// 上传文件后,生成缩略图,放在small文件夹下;
ScaleImage si = new ScaleImage();
String small = realPath + "/small";
String oPath = realPath + "/" + originalFilename.trim();
String thumbPath = small + "/" + originalFilename.trim();
//创建small文件夹
File smallDir = new File(small);
if(!smallDir.exists()){
smallDir.mkdirs();
}
si.saveImageAsJpg(oPath,thumbPath, 140, 90);
GYFtpClient ftp = new GYFTPClientImpl();
try {
ftp.setHostName("192.168.1.173");
ftp.setUserName("admin");
ftp.setPassword("admin");
ftp.setPort(21);
ftp.connect();
File file = new File(realPath);
ftp.upload("apply",file);
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
logger.info("文件[" + originalFilename+ "]上传失败,堆栈轨迹如下");
logger.error("异常", e);
out.print("1`文件上传失败,请重试!!");
out.flush();
return null;
}
}
}
}
out.print("0`" +"http://"+ip+":8080"+ request.getContextPath() + "/upload/"
+ originalFilename.trim());
out.print("#" + originalFilename.trim());
out.flush();
return null;
}
}
2)如果上传的是图片,生成缩略图的类
package com.gy.apply.admin.platform.contract.controller;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
/**
*
* Simple to Introduction
* @category Simple to Introduction
* @projectName person-web
* @package com.gy.person.util.ScaleImage.java
* @className ScaleImage
* @description 生成缩略图
* @author zhoudq
* @createDate 2014-8-27 下午4:59:54
* @updateUser zhoudq
* @updateDate 2014-8-27 下午4:59:54
* @updateRemark 说明本次修改内容
* @version v0.0.1
*/
public class ScaleImage {
private int width;
private int height;
private int scaleWidth;
double support = (double) 3.0;
double PI = (double) 3.14159265358978;
double[] contrib;
double[] normContrib;
double[] tmpContrib;
int startContrib, stopContrib;
int nDots;
int nHalfDots;
/**
* Start: Use Lanczos filter to replace the original algorithm for image
* scaling. Lanczos improves quality of the scaled image modify by :blade
*/
public static void main(String[] args) {
// ScaleImage is = new ScaleImage();
// try {
// is.saveImageAsJpg("E:/test/img/1409109501890catanddog.jpg", "E:/test/img/small/1409109501890catanddog.jpg", 120,
// 120);
// System.out.println("success");
// } catch (Exception e) {
// e.printStackTrace();
// }
}
/**
*
* @param fromFileStr 原图片地址
* @param saveToFileStr 生成缩略图地址
* @param formatWideth 生成图片宽度
* @param formatHeight formatHeight高度
*/
public void saveImageAsJpg(String fromFileStr, String saveToFileStr,
int formatWideth, int formatHeight) throws Exception {
BufferedImage srcImage;
File saveFile = new File(saveToFileStr);
File fromFile = new File(fromFileStr);
srcImage = javax.imageio.ImageIO.read(fromFile); // construct image
int imageWideth = srcImage.getWidth(null);
int imageHeight = srcImage.getHeight(null);
int changeToWideth = 0;
int changeToHeight = 0;
if (imageWideth > 0 && imageHeight > 0) {
// flag=true;
if (imageWideth / imageHeight >= formatWideth / formatHeight) {
if (imageWideth > formatWideth) {
changeToWideth = formatWideth;
changeToHeight = (imageHeight * formatWideth) / imageWideth;
} else {
changeToWideth = imageWideth;
changeToHeight = imageHeight;
}
} else {
if (imageHeight > formatHeight) {
changeToHeight = formatHeight;
changeToWideth = (imageWideth * formatHeight) / imageHeight;
} else {
changeToWideth = imageWideth;
changeToHeight = imageHeight;
}
}
}
srcImage = imageZoomOut(srcImage, changeToWideth, changeToHeight);
ImageIO.write(srcImage, "JPEG", saveFile);
}
public BufferedImage imageZoomOut(BufferedImage srcBufferImage, int w, int h) {
width = srcBufferImage.getWidth();
height = srcBufferImage.getHeight();
scaleWidth = w;
if (DetermineResultSize(w, h) == 1) {
return srcBufferImage;
}
CalContrib();
BufferedImage pbOut = HorizontalFiltering(srcBufferImage, w);
BufferedImage pbFinalOut = VerticalFiltering(pbOut, h);
return pbFinalOut;
}
/**
* 决定图像尺寸
*/
private int DetermineResultSize(int w, int h) {
double scaleH, scaleV;
scaleH = (double) w / (double) width;
scaleV = (double) h / (double) height;
// 需要判断一下scaleH,scaleV,不做放大操作
if (scaleH >= 1.0 && scaleV >= 1.0) {
return 1;
}
return 0;
} // end of DetermineResultSize()
private double Lanczos(int i, int inWidth, int outWidth, double Support) {
double x;
x = (double) i * (double) outWidth / (double) inWidth;
return Math.sin(x * PI) / (x * PI) * Math.sin(x * PI / Support)
/ (x * PI / Support);
}
private void CalContrib() {
nHalfDots = (int) ((double) width * support / (double) scaleWidth);
nDots = nHalfDots * 2 + 1;
try {
contrib = new double[nDots];
normContrib = new double[nDots];
tmpContrib = new double[nDots];
} catch (Exception e) {
System.out.println("init contrib,normContrib,tmpContrib" + e);
}
int center = nHalfDots;
contrib[center] = 1.0;
double weight = 0.0;
int i = 0;
for (i = 1; i <= center; i++) {
contrib[center + i] = Lanczos(i, width, scaleWidth, support);
weight += contrib[center + i];
}
for (i = center - 1; i >= 0; i--) {
contrib[i] = contrib[center * 2 - i];
}
weight = weight * 2 + 1.0;
for (i = 0; i <= center; i++) {
normContrib[i] = contrib[i] / weight;
}
for (i = center + 1; i < nDots; i++) {
normContrib[i] = normContrib[center * 2 - i];
}
} // end of CalContrib()
// 处理边缘
private void CalTempContrib(int start, int stop) {
double weight = 0;
int i = 0;
for (i = start; i <= stop; i++) {
weight += contrib[i];
}
for (i = start; i <= stop; i++) {
tmpContrib[i] = contrib[i] / weight;
}
} // end of CalTempContrib()
private int GetRedValue(int rgbValue) {
int temp = rgbValue & 0x00ff0000;
return temp >> 16;
}
private int GetGreenValue(int rgbValue) {
int temp = rgbValue & 0x0000ff00;
return temp >> 8;
}
private int GetBlueValue(int rgbValue) {
return rgbValue & 0x000000ff;
}
private int ComRGB(int redValue, int greenValue, int blueValue) {
return (redValue << 16) + (greenValue << 8) + blueValue;
}
// 行水平滤波
private int HorizontalFilter(BufferedImage bufImg, int startX, int stopX,
int start, int stop, int y, double[] pContrib) {
double valueRed = 0.0;
double valueGreen = 0.0;
double valueBlue = 0.0;
int valueRGB = 0;
int i, j;
for (i = startX, j = start; i <= stopX; i++, j++) {
valueRGB = bufImg.getRGB(i, y);
valueRed += GetRedValue(valueRGB) * pContrib[j];
valueGreen += GetGreenValue(valueRGB) * pContrib[j];
valueBlue += GetBlueValue(valueRGB) * pContrib[j];
}
valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
Clip((int) valueBlue));
return valueRGB;
} // end of HorizontalFilter()
// 图片水平滤波
private BufferedImage HorizontalFiltering(BufferedImage bufImage, int iOutW) {
int dwInW = bufImage.getWidth();
int dwInH = bufImage.getHeight();
int value = 0;
BufferedImage pbOut = new BufferedImage(iOutW, dwInH,
BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < iOutW; x++) {
int startX;
int start;
int X = (int) (((double) x) * ((double) dwInW) / ((double) iOutW) + 0.5);
int y = 0;
startX = X - nHalfDots;
if (startX < 0) {
startX = 0;
start = nHalfDots - X;
} else {
start = 0;
}
int stop;
int stopX = X + nHalfDots;
if (stopX > (dwInW - 1)) {
stopX = dwInW - 1;
stop = nHalfDots + (dwInW - 1 - X);
} else {
stop = nHalfDots * 2;
}
if (start > 0 || stop < nDots - 1) {
CalTempContrib(start, stop);
for (y = 0; y < dwInH; y++) {
value = HorizontalFilter(bufImage, startX, stopX, start,
stop, y, tmpContrib);
pbOut.setRGB(x, y, value);
}
} else {
for (y = 0; y < dwInH; y++) {
value = HorizontalFilter(bufImage, startX, stopX, start,
stop, y, normContrib);
pbOut.setRGB(x, y, value);
}
}
}
return pbOut;
} // end of HorizontalFiltering()
private int VerticalFilter(BufferedImage pbInImage, int startY, int stopY,
int start, int stop, int x, double[] pContrib) {
double valueRed = 0.0;
double valueGreen = 0.0;
double valueBlue = 0.0;
int valueRGB = 0;
int i, j;
for (i = startY, j = start; i <= stopY; i++, j++) {
valueRGB = pbInImage.getRGB(x, i);
valueRed += GetRedValue(valueRGB) * pContrib[j];
valueGreen += GetGreenValue(valueRGB) * pContrib[j];
valueBlue += GetBlueValue(valueRGB) * pContrib[j];
// System.out.println(valueRed+"->"+Clip((int)valueRed)+"<-");
//
// System.out.println(valueGreen+"->"+Clip((int)valueGreen)+"<-");
// System.out.println(valueBlue+"->"+Clip((int)valueBlue)+"<-"+"-->");
}
valueRGB = ComRGB(Clip((int) valueRed), Clip((int) valueGreen),
Clip((int) valueBlue));
// System.out.println(valueRGB);
return valueRGB;
} // end of VerticalFilter()
private BufferedImage VerticalFiltering(BufferedImage pbImage, int iOutH) {
int iW = pbImage.getWidth();
int iH = pbImage.getHeight();
int value = 0;
BufferedImage pbOut = new BufferedImage(iW, iOutH,
BufferedImage.TYPE_INT_RGB);
for (int y = 0; y < iOutH; y++) {
int startY;
int start;
int Y = (int) (((double) y) * ((double) iH) / ((double) iOutH) + 0.5);
startY = Y - nHalfDots;
if (startY < 0) {
startY = 0;
start = nHalfDots - Y;
} else {
start = 0;
}
int stop;
int stopY = Y + nHalfDots;
if (stopY > (int) (iH - 1)) {
stopY = iH - 1;
stop = nHalfDots + (iH - 1 - Y);
} else {
stop = nHalfDots * 2;
}
if (start > 0 || stop < nDots - 1) {
CalTempContrib(start, stop);
for (int x = 0; x < iW; x++) {
value = VerticalFilter(pbImage, startY, stopY, start, stop,
x, tmpContrib);
pbOut.setRGB(x, y, value);
}
} else {
for (int x = 0; x < iW; x++) {
value = VerticalFilter(pbImage, startY, stopY, start, stop,
x, normContrib);
pbOut.setRGB(x, y, value);
}
}
}
return pbOut;
} // end of VerticalFiltering()
int Clip(int x) {
if (x < 0)
return 0;
if (x > 255)
return 255;
return x;
}
}
2.上传文件到ftp
1)处理上传文件到ftp的接口
package com.gy.common.attach;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import org.apache.commons.net.ftp.FTPClient;
/**
* Simple to Introduction
*
* @category Simple to Introduction
* @projectName common-attach
* @package com.gy.common.attach.GYFtpClient.java
* @className GYFtpClient
* @description 上传文件至ftp 接口类
* @author hexy
* @createDate 2014-10-13 下午12:04:32
* @updateUser hexy
* @updateDate 2014-10-13 下午12:04:32
* @updateRemark 说明本次修改内容
* @version v0.0.1
*/
public interface GYFtpClient {
/**
*
* 连接到FTP服务器
*
* @return 是否连接成功
* @throws IOException
*/
public boolean connect() throws IOException;
/**
*
* 连接到FTP服务器,端口默认为21
*
* @param hostname
* 主机名
* @param username
* 用户名
* @param password
* 密码
* @return 是否连接成功
* @throws IOException
*/
public boolean connect(String hostname, String username, String password)
throws IOException;
/**
*
* 连接到FTP服务器
*
* @param hostname
* 主机名
* @param port
* 端口
* @param username
* 用户名
* @param password
* 密码
* @return 是否连接成功
* @throws IOException
*/
public boolean connect(String hostname, int port, String username,
String password) throws IOException;
/**
* 断开与远程服务器的连接
*
* @throws IOException
*/
public void disconnect() throws IOException;
/**
* 上传文件到FTP服务器,支持目录和断点续传
*
* @param subSystemName
* 子系统名称
* @param local
* 本地文件
* @return 上传结果
* @throws Exception
*/
public Map<Object, String> upload(String subSystemName, File local)
throws Exception;
/**
* 断点续传
*
* @param remoteFile
* 待上传的文件名
* @param localFile
* 待上传的文件
* @param ftpClient
*
* @param remoteSize
*
* @return 上传结果
* @throws Exception
*/
public UploadStatus uploadFile(String remoteFile, File localFile,
FTPClient ftpClient, long remoteSize) throws IOException;
/**
*
* 递归创建远程服务器目录
*
* @param remote
* 远程服务器文件绝对路径
* @param ftpClient
* FTPClient 对象
* @return 目录创建是否成功
* @throws IOException
*/
public UploadStatus CreateDirecroty(String remote, FTPClient ftpClient)
throws IOException;
public void setHostName(String string);
public void setUserName(String string);
public void setPassword(String string);
public void setPort(int port);
}
2)处理上传文件到ftp的实现类
package com.gy.common.attach;
import static com.gy.common.utils.DateUtil.DATE_FORMAT;
import static com.gy.common.utils.DateUtil.DateToString;
import static com.gy.common.utils.DateUtil.getCurrentDate;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;
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;
import com.gy.common.log.GyLogger;
/**
* Simple to Introduction
* @category Simple to Introduction
* @projectName common-attach
* @package com.gy.common.attach.GYFTPClientImpl.java
* @className GYFTPClientImpl
* @description 上传文件至ftp 实现类
* @author hexy
* @createDate 2014-10-13 下午2:14:47
* @updateUser hexy
* @updateDate 2014-10-13 下午2:14:47
* @updateRemark 说明本次修改内容
* @version v0.0.1
*/
public class GYFTPClientImpl implements GYFtpClient {
protected GyLogger logger = GyLogger.getLogger(this.getClass());
private FTPClient ftpClient = new FTPClient();
boolean flag = true;
private String hostName;
private int port;
private String password;
private String userName;
public GYFTPClientImpl(String hostName, String userName, String password) {
super();
this.hostName = hostName;
this.userName = userName;
this.password = password;
}
public GYFTPClientImpl(String hostName, int port, String userName,
String password) {
super();
this.hostName = hostName;
this.port = port;
this.userName = userName;
this.password = password;
}
public GYFTPClientImpl() {
}
@Override
public boolean connect() throws IOException {
return connect(hostName, port, userName, password);
}
@Override
public boolean connect(String hostname, String username, String password)
throws IOException {
return this.connect(hostname, 0, username, password);
}
@Override
public boolean connect(String hostname, int port, String username,
String password) throws IOException {
if (port == 0) {
ftpClient.connect(hostname);
} else {
ftpClient.connect(hostname, port);
}
ftpClient.setControlEncoding("UTF-8");
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
if (ftpClient.login(username, password)) {
return true;
}
}
disconnect();
return false;
}
@Override
public void disconnect() throws IOException {
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
}
/**
*
* @param file
* 上传的文件或文件夹
* @throws Exception
*/
@Override
public Map<Object, String> upload(String subSystemName, File file)
throws Exception {
// 判断subSystemName是否存在
if (!SubSystemName.isSubSystemName(subSystemName)) {
String msg = "No support subSystemName: " + subSystemName;
logger.error(msg);
throw new RuntimeException(msg);
}
if (flag) {
// 创建apply目录
String path = subSystemName;
ftpClient.makeDirectory(path);
ftpClient.changeWorkingDirectory(path);
// 创建日期目录
path = getDateForDir();
ftpClient.makeDirectory(path);
ftpClient.changeWorkingDirectory(path);
flag = false;
}
Map<Object, String> result = new HashMap<Object, String>();
if (file.isDirectory()) {
ftpClient.makeDirectory(file.getName());
ftpClient.changeWorkingDirectory(file.getName());
String[] files = file.list();
for (int i = 0; i < files.length; i++) {
File subDir = new File(file.getPath() + "/" + files[i]);
if (subDir.isDirectory()) {
upload(subSystemName, subDir);
ftpClient.changeToParentDirectory();
} else {
File subFile = new File(file.getPath() + "/" + files[i]);
result = preUpload(subFile, subFile.getName());
}
}
} else {
File bfile = new File(file.getPath());
result = preUpload(bfile, bfile.getName());
}
return result;
}
/**
*
* @param local
* @param remote
* 上传文件
* @throws Exception
*/
private Map<Object, String> preUpload(File local, String remote)
throws Exception {
Map<Object, String> result = new HashMap<Object, String>();
// 设置PassiveMode传输
ftpClient.enterLocalPassiveMode();
// 设置以二进制流的方式传输
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setControlEncoding("UTF-8");
// 对远程目录的处理
String remoteFileName = remote;
if (remote.contains("/")) {
remoteFileName = remote.substring(remote.lastIndexOf("/") + 1);
// 创建服务器远程目录结构,创建失败直接返回
if (CreateDirecroty(remote, ftpClient) == UploadStatus.Create_Directory_Fail) {
result.put(UploadStatus.Create_Directory_Fail, hostName
+ "/ftp/" + remote);
return result;
}
}
// 检查远程是否存在文件
FTPFile[] files = ftpClient.listFiles(new String(remoteFileName
.getBytes("UTF-8"), "ISO-8859-1"));
if (files.length == 1) {
long remoteSize = files[0].getSize();
long localSize = local.length();
if (remoteSize == localSize) {
result.put(UploadStatus.File_Exits, hostName + "/ftp/" + remote);
return result;
} else if (remoteSize > localSize) {
result.put(UploadStatus.Remote_Bigger_Local, hostName + "/ftp/"
+ remote);
return result;
}
} else {//远程不存在则上传
uploadFile(remoteFileName, local, ftpClient, 0);
}
return result;
}
/**
* 得到当前日期
* @return
*/
private String getDateForDir() {
return DateToString(getCurrentDate(DATE_FORMAT), DATE_FORMAT);
}
/**
* 断点续传
*/
@Override
public UploadStatus uploadFile(String remoteFile, File localFile,
FTPClient ftpClient, long remoteSize) throws IOException {
UploadStatus status;
// 显示进度的上传
long step = localFile.length() / 100;
long process = 0;
long localreadbytes = 0L;
RandomAccessFile raf = new RandomAccessFile(localFile, "r");
OutputStream out = ftpClient.appendFileStream(new String(remoteFile
.getBytes("UTF-8"), "ISO-8859-1"));
// 断点续传
if (remoteSize > 0) {
ftpClient.setRestartOffset(remoteSize);
process = remoteSize / step;
raf.seek(remoteSize);
localreadbytes = remoteSize;
}
byte[] bytes = new byte[1024];
int c;
while ((c = raf.read(bytes)) != -1) {
out.write(bytes, 0, c);
localreadbytes += c;
if (localreadbytes / step != process) {
process = localreadbytes / step;
System.out.println("上传进度:" + process);
// 汇报上传状态
}
}
out.flush();
raf.close();
out.close();
boolean result = ftpClient.completePendingCommand();
if (remoteSize > 0) {
status = result ? UploadStatus.Upload_From_Break_Success
: UploadStatus.Upload_From_Break_Failed;
} else {
status = result ? UploadStatus.Upload_New_File_Success
: UploadStatus.Upload_New_File_Failed;
}
return status;
}
/**
* 创建远程目录
*/
@Override
public UploadStatus CreateDirecroty(String remote, FTPClient ftpClient)
throws IOException {
UploadStatus status = UploadStatus.Create_Directory_Success;
String directory = remote.substring(0, remote.lastIndexOf("/") + 1);
if (!directory.equalsIgnoreCase("/")
&& !ftpClient.changeWorkingDirectory(new String(directory
.getBytes("UTF-8"), "ISO-8859-1"))) {
// 如果远程目录不存在,则递归创建远程服务器目录
int start = 0;
int end = 0;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
while (true) {
String subDirectory = new String(remote.substring(start, end)
.getBytes("UTF-8"), "ISO-8859-1");
if (!ftpClient.changeWorkingDirectory(subDirectory)) {
if (ftpClient.makeDirectory(subDirectory)) {
ftpClient.changeWorkingDirectory(subDirectory);
} else {
System.out.println("创建目录失败");
return UploadStatus.Create_Directory_Fail;
}
}
start = end + 1;
end = directory.indexOf("/", start);
// 检查所有目录是否创建完毕
if (end <= start) {
break;
}
}
}
return status;
}
@Override
public void setHostName(String hostName) {
this.hostName = hostName;
}
public String getHostName() {
return hostName;
}
@Override
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public void setPassword(String password) {
this.password = password;
}
public String getPassword() {
return password;
}
public String getUserName() {
return userName;
}
public int getPort() {
return port;
}
@Override
public void setPort(int port) {
this.port = port;
}
}
3)状态描述类
package com.gy.common.attach;
/**
* Simple to Introduction
*
* @category Simple to Introduction
* @projectName GYFtpClient
* @package com.gy.common.ftp.UploadStatus.java
* @className UploadStatus
* @description 上传文件至ftp 状态描述类
* @author hexy
* @createDate 2014-10-10 上午11:10:36
* @updateUser hexy
* @updateDate 2014-10-10 上午11:10:36
* @updateRemark 增加
* @version v0.0.1
*/
public enum UploadStatus {
/** 远程服务器相应目录创建失败 */
Create_Directory_Fail,
/** 远程服务器闯将目录成功 */
Create_Directory_Success,
/** 上传新文件成功 */
Upload_New_File_Success,
/** 上传新文件失败 */
Upload_New_File_Failed,
/** 文件已经存在 */
File_Exits,
/** 远程文件大于本地文件 */
Remote_Bigger_Local,
/** 断点续传成功 */
Upload_From_Break_Success,
/** 断点续传失败 */
Upload_From_Break_Failed,
/** 删除远程文件失败 */
Delete_Remote_Faild;
}