权3914 发表于 2016-6-9 11:02:14

java图片处理并上传ftp

在手机应用或者网站开发中,很多情况我们需要将图片或文件上传ftp服务器,应用时只需返回一个路径。
第一、如果没有现有的ftp服务器,可以在本机自行搭建一个测试服务器。
第二、如何连接服务器
      创建一个上传服务器类ftpUpload,首先定义ftp服务器的ip,用户的id,密码,和端口,然后创建实例,并将参数附上值,
public FtpUpload() throws IOException {         
this.ip=this.ip;   
this.userId=this.userId;   
this.pwd=this.pwd;
this.port=this.port; }   
第三、上传文件:通过ip和端口连接ftp服务器,验证用户名和密码,判断文件夹是否已经存在,指定工作目录,
       public boolean upMyFile(String fileName,InputStream ins){         
FTPClient ftpClient = new FTPClient();      
ftpClient.setControlEncoding("GBK");   
try {         
ftpClient.connect(ip, port);            
if (!ftpClient.login(userId, pwd)) {               
System.out.println("系统登录不成功!");               
}               
DateFormat df = new SimpleDateFormat("yyyyMMdd");            
String strDate=df.format(new Date());
if (ftpClient.cwd(strDate) == 250) { // 若返回值为250,说明文件夹已经存在            
ftpClient.cwd(strDate); // 指定工作目录   
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
if (ftpClient.storeFile(fileName, ins)) {               
file=strDate+"/"+fileName;            
}else{               
return false;            
}            
ftpClient.logout();
} else {            
ftpClient.makeDirectory(strDate);               
ftpClient.cwd(strDate);         
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);            
if (ftpClient.storeFile(fileName, ins)) {               
file=strDate+"/"+fileName;            
}else{               
return false;            
}            
ftpClient.logout();            
}
} catch (SocketException e) {               
e.printStackTrace();               
return false;      
} catch (IOException e) {               
e.printStackTrace();               
return false;      
}
return true;
}   
}

上传类已经写好,然后可以写一个测试程序处理图片并通过上面的类上传
当获得一个MultipartFile型的文件file时,将文件转换成byte数组,如果想把获得的图片大小变成固定的,只需给定相应的宽高
byte[] bytes = null;
int height = 600;
int width = 800
bytes = file.getBytes();
InputStream buffin = new ByteArrayInputStream(bytes);
BufferedImage img = ImageIO.read(buffin);

然后new一个上面的ftpUpload上传类,将图片转换成流的形式
FtpUpload ftpUpload=new FtpUpload();
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
image.getGraphics().drawImage(img,0,0, width, height, null);
java.io.ByteArrayOutputStream   output   =   new   java.io.ByteArrayOutputStream();
ImageIO.write(image,   "jpg",   output);
byte[]   buff   =   output.toByteArray();
InputStream   in   =   new ByteArrayInputStream(buff);

重新命名图片名称,可以以当前上传时间(yyyyMMddHHmmss)为名

DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");            
String sysTime=df.format(new Date());   
ftpUpload.upMyFile(sysTime+".jpg",in);
页: [1]
查看完整版本: java图片处理并上传ftp