您的位置:首页 > 编程语言 > Java开发

java上传图片到ftp

2010-03-30 14:31 337 查看
最近在弄新闻编辑后台的管理程序,由于公司没有图片服务器,后台的程序和前台的程序分离。前台和后台都是部署在集群上。要想共享上传的图片,我们在每台机器上开了个ftp。在提交的时候同时将文件上传到ftp上。

页面展示选择了kindEdit js框架。

上传本地图片到服务器的程序如下:

<%@ page pageEncoding="gbk"%>
<%@page
import="java.util.*,java.io.*,
org.apache.commons.fileupload.FileItem,
org.apache.commons.fileupload.FileUploadException,
org.apache.commons.fileupload.disk.DiskFileItemFactory,
org.apache.commons.fileupload.servlet.ServletFileUpload,
java.util.concurrent.locks.*,
com.glot.csp.lottery.common.ftp.*"%>
<%
String id = "";
String url = "";
String imgTitle = "";
String imgWidth = "";
String imgHeight = "";
String imgBorder = "";
String filePath = "";
String align = "";
// **************************************
// 初始化上传工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置上传工厂对象限制
factory.setSizeThreshold(1024 * 1024 * 20);
factory.setRepository(new File(request.getSession(true)
.getServletContext().getRealPath("/")));
// 创建上传对象
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(1024 * 1024 * 20);
List items = null;
System.out.println("*************MMMM&&&&&&&&&");
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace(System.out);
}
for (Iterator i = items.iterator(); i.hasNext();) {
FileItem item = (FileItem)i.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("gbk");
if (name.equals("id")) {
id = value;
} else if (name.equals("imgTitle")) {
imgTitle = value;
} else if (name.equals("imgWidth")) {
imgWidth = value;
} else if (name.equals("imgHeight")) {
imgHeight = value;
} else if (name.equals("imgBorder")) {
imgBorder = value;
} else if (name.equals("align")) {
align = value;
} else if (name.equals("url")) {
filePath = value;
}
} else {
// 取得表单域名
String fieldName = item.getFieldName();
// 取得文件名
String fileName = item.getName();
// 取得文件类型
String contentType = item.getContentType();

final Lock lock = new ReentrantLock();
String newName = null;
lock.lock();
try {
//加锁为防止同一时间文件名冲突
newName = System.currentTimeMillis()
+ fileName.substring(fileName.lastIndexOf("."),
fileName.length());
} catch (Exception e) {
e.printStackTrace(System.err);
} finally {
lock.unlock();
}
filePath = "./ke_upload/" + newName;
File file = new File(request.getSession()
.getServletContext().getRealPath("/")
+ "//ke_upload");
if (!file.exists()) {
file.mkdirs();
}
String path = request
.getSession().getServletContext().getRealPath("/")
+ "//ke_upload//" + newName;
FileOutputStream fos = new FileOutputStream(path);
if (item.isInMemory()) {
fos.write(item.get());
fos.close();
} else {
InputStream in = item.getInputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
in.close();
fos.close();

}
new TransferFileFtp().copyFileToFtp(path);
}
}
out.println("<html><head><title>Insert Image</title><meta http-equiv='content-type' content='text/html; charset=gbk'/></head><body>");
out.println("<script type='text/javascript'>");
out.println("parent.parent.KE.plugin['image'].insert('" + id
+ "','" + filePath + "','" + imgTitle + "','" + imgWidth
+ "','" + imgHeight + "','" + imgBorder + "','" + align
+ "');</script>");
out.println("</body></html>");
%>

由服务器上传图片到ftp的代码如下:

package com.glot.csp.lottery.common.ftp;

import java.io.FileInputStream;
import java.io.IOException;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;

public class TransferFileFtp {
static FtpClient ftpClient;

private Configuration configura = Configuration.getInstance();

/**
* 连接FTP、复制文件
*
* @throws Exception
*/
public boolean copyFileToFtp(String path) throws Exception {

try {
ftpConnect();

if (!isExistDir(configura.getValue("ftpFilePath")))
mkDir(configura.getValue("ftpFilePath"));

String[] sFileName;

System.out.println(ftpClient.pwd());

sFileName = path.split(configura.getValue("splitString"));

TelnetOutputStream ftpOut = ftpClient
.put(sFileName[sFileName.length - 1]);

FileInputStream fs = new FileInputStream(path);
TelnetInputStream ftpIn = new TelnetInputStream(fs, true);
byte[] buf = new byte[204800];
int bufsize = 0;
while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
ftpOut.write(buf, 0, bufsize);
}

ftpIn.close();
ftpOut.close();

System.out.println(ftpClient.getResponseString());

} catch (IOException e) {
e.printStackTrace();
return false;
}
ftpClient.sendServer("QUIT/r/n");
return true;
}

/**
* 连接FTP
*
*/
private void ftpConnect() {
try {
ftpClient = new FtpClient(configura.getValue("ipAdress"), Integer
.parseInt(configura.getValue("port")));
ftpClient.login(configura.getValue("userName"), configura
.getValue("passWord"));
ftpClient.binary();//避免传递的图片失真
System.out.println(ftpClient.welcomeMsg);
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 判断ftp上是否存在路径
*
* @return boolean
*/
private boolean isExistDir(String path) {
try {
ftpClient.cd(path);
} catch (IOException e) {
return false;
}
return true;
}

/**
* 在ftp上创建文件夹
*
* @param dir
* 文件夹名字
*/
private void mkDir(String dir) {

ftpClient.sendServer("MKD " + dir + "/r/n");

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: