jsp 上传文件到两台服务器。
2012-02-21 15:18
155 查看
应用环境:服务器是windows2003。
服务器:两台服务器web服务器和数据库服务器。
实现的目标:在web服务器端进行文件的上传,上传后的文件传输到数据库服务器。
所需条件:在web服务器上要有相应的目录存储文件,假设为:D:\\webroot\\Project\\public\\usertel\\。在数据库服务器上要有一个共享的文件夹,假设命名为ttt,所需jar包:jcifs-1.3.14.jar(网上可以下载找到)。
写一个上传文件的jsp页面:
<%
//检查表单是否正确
boolean isMultipart = FileUpload.isMultipartContent(request);
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String time1 = new SimpleDateFormat("yyyyMMddhhmmss").format(Calendar.getInstance().getTime());
//文件最大,设为-1表示不受限制
//upload.setSizeMax(50*1024);
//解析请求,把解析的结果放在一个List里面
List items = upload.parseRequest(request);
//缓存大小,设为-1表示不受限制
factory.setSizeThreshold(4096);
//设置临时目录
factory.setRepository(new File("D:\\temp"));
Iterator iter = items.iterator();
String dirtemp1 = null;
String c_filename = null;
String dirtemp = null;
while(iter.hasNext()){
FileItem item = (FileItem)iter.next();
//检查是一个普通的表单域还是File组件
if(!item.isFormField()){
File fullFile = new File(item.getName());
String filepath1="/public/usertel/";
String filepath = "\\usertel\\";
String s = request.getContextPath();
//System.out.println("s"+s);
s = s +filepath1;
String path = application.getRealPath("/").substring(0,application.getRealPath("/").length()) + request.getRequestURI().substring(request.getContextPath().length());
//System.out.println(path);
//String strDirPathttt = new File(pathttt).getParent();//获取upload.jsp页面所在路径。
String strDirPath = new File(path).getParent();//获取upload.jsp页面所在路径。
filepath = strDirPath + filepath;
//System.out.println("路径:"+filepath);
c_filename = fullFile.getName();
if(c_filename==null || c_filename.equals("")){
dirtemp = null;
}else{
c_filename = time1.concat(".xls");
File uploadedFile = new File(filepath,c_filename;
dirtemp = s.concat(c_filename);
//System.out.println(filepath);
dirtemp1 = filepath.concat(c_filename);
item.write(uploadedFile);
boolean tag = FileTransfer.Transferable(c_filename);//******************
这是调用的将文件传到数据库服务器的方法。
if(tag==true){
System.out.println("上传成功");
}
}
}
}
%>
以下是FileTransfer方法(这部分主要是借鉴了他人的用法。):
public class FileTransfer {
private static Logger logger = Logger.getLogger(FileTransfer.class);
private static final int BUFFERED_NUM = 16 * 1024;
public static boolean Transferable(String filename){
try {
String localDir = "D:\\webroot\\Project\\public\\usertel\\"+filename;
String remoteUrl = "smb://Administrator:password@192.168.9.103/ttt/"+filename;//Administrator是数据库服务器的用户名,password为数据库服务器的密码。
int offset = 0;
writeFileToRemote(localDir, remoteUrl, offset);
System.out.println("-----end");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
/**
* 写文件到远程服务器上。
*
* @param localDir
* @param remoteUrl
* @param offset
* @throws IOException
* @since 0.9
*/
public static void writeFileToRemote(String localDir, String remoteUrl,
int offset) throws Exception {
logger.info("---writeFile start....localDir=" + localDir
+ "...remoteUrl=" + remoteUrl + "...offset=" + offset);
System.out.println(localDir);
System.out.println(remoteUrl);
if (remoteUrl == null || remoteUrl.trim().equals("")
|| localDir == null || localDir.trim().equals("")) {
throw new Exception(
"---remoteUrl or localDir is null or is nlank!---");
}
// 检验要写入文件的文件夹是否存在。检验完后一定存在。
checkSmbFilePath(remoteUrl);
String remoteUrlNew = remoteUrl;
remoteUrl = remoteUrl + ".unimas";
// 读写文件
byte buffer[] = new byte[BUFFERED_NUM];
int readed = 0;
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
// println(remoteUrl + "....localDir=" + localDir);
SmbFile remoteFile = new SmbFile(remoteUrl);
in = new BufferedInputStream(new FileInputStream(localDir),
BUFFERED_NUM);
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile),
BUFFERED_NUM);
if (offset > 0) {
// 读取不需要的信息。
in.read(new byte[offset]);
}
// 建立smb文件输入流
while ((readed = in.read(buffer)) != -1) {
out.write(buffer, 0, readed);
}
out.close();
in.close();
logger.info("---writeFile end....localDir=" + localDir
+ "...remoteUrl=" + remoteUrl + "...offset=" + offset);
// TODO 增加换名的操作
SmbFile remoteFile2 = new SmbFile(remoteUrlNew);
// 先判断是否存在,若存在,则删除
if (remoteFile2.exists()) {
remoteFile2.delete();
}
remoteFile.renameTo(remoteFile2);
logger.info("---rename....old=" + remoteUrl + "...new="
+ remoteUrlNew + "...success!");
remoteUrl = remoteUrlNew;
} catch (Exception e) {
closeBufferedOutputStream(out);
closeBufferedInputStream(in);
// 删除远程文件
SmbFile remoteFile = new SmbFile(remoteUrl);
if (remoteFile.exists()) {
remoteFile.delete();
logger.info("---writeFile fail....localDir=" + localDir
+ "...remoteUrl=" + remoteUrl + "...delete remote!");
}
throw e;
} finally {
closeBufferedOutputStream(out);
closeBufferedInputStream(in);
}
}
/**
* 关闭缓冲输入流。
*
* @param bais
* @since 1.0
*/
public static void closeBufferedOutputStream(BufferedOutputStream bais) {
if (bais != null) {
try {
bais.close();
} catch (IOException e) {
logger.error("close BufferedOutputStream faild");
logger.error(e);
}
bais = null;
}
}
/**
* 关闭缓冲流。
*
* @param bais
* @since 1.0
*/
protected static void closeBufferedInputStream(BufferedInputStream bais) {
if (bais != null) {
try {
bais.close();
} catch (IOException e) {
logger.error("close BufferedInputStream faild");
logger.error(e);
}
bais = null;
}
}
public static void checkSmbFilePath(String remoteUrl) throws Exception {
// 获取给定文件对应的目录
int temp1 = remoteUrl.lastIndexOf("//");
int temp2 = remoteUrl.lastIndexOf("/");
if (temp2 > temp1) {
temp1 = temp2;
}
String path = remoteUrl.substring(0, temp1);
if (!createFolder(path)) {
throw new Exception("---" + path + " is not exists---");
}
}
/**
* 创建目录。
*
* @param parentPath
* 给定的目录名。
* @return 已存在或创建成功返回true,否则返回false。
* @throws MalformedURLException
* @throws SmbException
* @since 0.9
*/
private static boolean createFolder(String parentPath)
throws MalformedURLException, SmbException {
if (parentPath == null) {
return false;
}
SmbFile path = new SmbFile(parentPath);
if (!path.exists()) {
path.mkdirs();
}
return true;
}
}
服务器:两台服务器web服务器和数据库服务器。
实现的目标:在web服务器端进行文件的上传,上传后的文件传输到数据库服务器。
所需条件:在web服务器上要有相应的目录存储文件,假设为:D:\\webroot\\Project\\public\\usertel\\。在数据库服务器上要有一个共享的文件夹,假设命名为ttt,所需jar包:jcifs-1.3.14.jar(网上可以下载找到)。
写一个上传文件的jsp页面:
<%
//检查表单是否正确
boolean isMultipart = FileUpload.isMultipartContent(request);
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
String time1 = new SimpleDateFormat("yyyyMMddhhmmss").format(Calendar.getInstance().getTime());
//文件最大,设为-1表示不受限制
//upload.setSizeMax(50*1024);
//解析请求,把解析的结果放在一个List里面
List items = upload.parseRequest(request);
//缓存大小,设为-1表示不受限制
factory.setSizeThreshold(4096);
//设置临时目录
factory.setRepository(new File("D:\\temp"));
Iterator iter = items.iterator();
String dirtemp1 = null;
String c_filename = null;
String dirtemp = null;
while(iter.hasNext()){
FileItem item = (FileItem)iter.next();
//检查是一个普通的表单域还是File组件
if(!item.isFormField()){
File fullFile = new File(item.getName());
String filepath1="/public/usertel/";
String filepath = "\\usertel\\";
String s = request.getContextPath();
//System.out.println("s"+s);
s = s +filepath1;
String path = application.getRealPath("/").substring(0,application.getRealPath("/").length()) + request.getRequestURI().substring(request.getContextPath().length());
//System.out.println(path);
//String strDirPathttt = new File(pathttt).getParent();//获取upload.jsp页面所在路径。
String strDirPath = new File(path).getParent();//获取upload.jsp页面所在路径。
filepath = strDirPath + filepath;
//System.out.println("路径:"+filepath);
c_filename = fullFile.getName();
if(c_filename==null || c_filename.equals("")){
dirtemp = null;
}else{
c_filename = time1.concat(".xls");
File uploadedFile = new File(filepath,c_filename;
dirtemp = s.concat(c_filename);
//System.out.println(filepath);
dirtemp1 = filepath.concat(c_filename);
item.write(uploadedFile);
boolean tag = FileTransfer.Transferable(c_filename);//******************
这是调用的将文件传到数据库服务器的方法。
if(tag==true){
System.out.println("上传成功");
}
}
}
}
%>
以下是FileTransfer方法(这部分主要是借鉴了他人的用法。):
public class FileTransfer {
private static Logger logger = Logger.getLogger(FileTransfer.class);
private static final int BUFFERED_NUM = 16 * 1024;
public static boolean Transferable(String filename){
try {
String localDir = "D:\\webroot\\Project\\public\\usertel\\"+filename;
String remoteUrl = "smb://Administrator:password@192.168.9.103/ttt/"+filename;//Administrator是数据库服务器的用户名,password为数据库服务器的密码。
int offset = 0;
writeFileToRemote(localDir, remoteUrl, offset);
System.out.println("-----end");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
/**
* 写文件到远程服务器上。
*
* @param localDir
* @param remoteUrl
* @param offset
* @throws IOException
* @since 0.9
*/
public static void writeFileToRemote(String localDir, String remoteUrl,
int offset) throws Exception {
logger.info("---writeFile start....localDir=" + localDir
+ "...remoteUrl=" + remoteUrl + "...offset=" + offset);
System.out.println(localDir);
System.out.println(remoteUrl);
if (remoteUrl == null || remoteUrl.trim().equals("")
|| localDir == null || localDir.trim().equals("")) {
throw new Exception(
"---remoteUrl or localDir is null or is nlank!---");
}
// 检验要写入文件的文件夹是否存在。检验完后一定存在。
checkSmbFilePath(remoteUrl);
String remoteUrlNew = remoteUrl;
remoteUrl = remoteUrl + ".unimas";
// 读写文件
byte buffer[] = new byte[BUFFERED_NUM];
int readed = 0;
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
// println(remoteUrl + "....localDir=" + localDir);
SmbFile remoteFile = new SmbFile(remoteUrl);
in = new BufferedInputStream(new FileInputStream(localDir),
BUFFERED_NUM);
out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile),
BUFFERED_NUM);
if (offset > 0) {
// 读取不需要的信息。
in.read(new byte[offset]);
}
// 建立smb文件输入流
while ((readed = in.read(buffer)) != -1) {
out.write(buffer, 0, readed);
}
out.close();
in.close();
logger.info("---writeFile end....localDir=" + localDir
+ "...remoteUrl=" + remoteUrl + "...offset=" + offset);
// TODO 增加换名的操作
SmbFile remoteFile2 = new SmbFile(remoteUrlNew);
// 先判断是否存在,若存在,则删除
if (remoteFile2.exists()) {
remoteFile2.delete();
}
remoteFile.renameTo(remoteFile2);
logger.info("---rename....old=" + remoteUrl + "...new="
+ remoteUrlNew + "...success!");
remoteUrl = remoteUrlNew;
} catch (Exception e) {
closeBufferedOutputStream(out);
closeBufferedInputStream(in);
// 删除远程文件
SmbFile remoteFile = new SmbFile(remoteUrl);
if (remoteFile.exists()) {
remoteFile.delete();
logger.info("---writeFile fail....localDir=" + localDir
+ "...remoteUrl=" + remoteUrl + "...delete remote!");
}
throw e;
} finally {
closeBufferedOutputStream(out);
closeBufferedInputStream(in);
}
}
/**
* 关闭缓冲输入流。
*
* @param bais
* @since 1.0
*/
public static void closeBufferedOutputStream(BufferedOutputStream bais) {
if (bais != null) {
try {
bais.close();
} catch (IOException e) {
logger.error("close BufferedOutputStream faild");
logger.error(e);
}
bais = null;
}
}
/**
* 关闭缓冲流。
*
* @param bais
* @since 1.0
*/
protected static void closeBufferedInputStream(BufferedInputStream bais) {
if (bais != null) {
try {
bais.close();
} catch (IOException e) {
logger.error("close BufferedInputStream faild");
logger.error(e);
}
bais = null;
}
}
public static void checkSmbFilePath(String remoteUrl) throws Exception {
// 获取给定文件对应的目录
int temp1 = remoteUrl.lastIndexOf("//");
int temp2 = remoteUrl.lastIndexOf("/");
if (temp2 > temp1) {
temp1 = temp2;
}
String path = remoteUrl.substring(0, temp1);
if (!createFolder(path)) {
throw new Exception("---" + path + " is not exists---");
}
}
/**
* 创建目录。
*
* @param parentPath
* 给定的目录名。
* @return 已存在或创建成功返回true,否则返回false。
* @throws MalformedURLException
* @throws SmbException
* @since 0.9
*/
private static boolean createFolder(String parentPath)
throws MalformedURLException, SmbException {
if (parentPath == null) {
return false;
}
SmbFile path = new SmbFile(parentPath);
if (!path.exists()) {
path.mkdirs();
}
return true;
}
}
相关文章推荐
- MyEclipse------如何添加jspsmartupload.jar+文件上传到服务器
- JSP多文件上传到服务器
- 【转载】使用jsp实现文件上传到服务器或者从服务器上下载文件到本地计算机完整说明版
- jsp页面上传图片文件到服务器页面无刷新的技巧
- JSP上传文件至服务器【2】
- 利用jsp+uploadify插件实现删除上传到ftp服务器里面的文件
- java+jsp代码实现从FTP服务器上传下载文件
- JSP + Servlet 实现的文件上传到服务器的功能
- JSP上传文件至服务器【1】
- JSP+Servlet使用jspsmartupload实现文件上传至服务器
- 【转载】使用jsp实现文件上传到服务器或者从服务器上下载文件到本地计算机完整说明版
- iOS文件处理,将图片存到手机目录里面 创建文件夹,NSFileManager用来存储图片,然后遍历将图片取出上传到服务器哦!!
- MVC分层+JDBC+数据库+Servlet实现JSP文件上传和显示+模糊查询+分页
- Java / JSP 文件上传与下载
- [asp,jsp,asp.net]文件上传技术浅议~~
- xftp连接服务器上传文件时,文件显示0字节。
- Jsp+Servlet实现文件上传下载(一)--文件上传
- [asp,jsp,asp.net]文件上传技术浅议~~
- jsp文件上传下载