1首先在客户端与服务器端传递序列化的对象
// 获得请求链接 ~~
//httpUrl是WEB应用的访问基路径,method是SERVLET名字,或者是基于struts的ACTION里的方法
private static URLConnection getCon(String httpUrl, String method)
throws Exception ...{
java.net.URL url = new java.net.URL(httpUrl + method);
java.net.URLConnection con = url.openConnection();
con.setUseCaches(true);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-type", "application/octest-stream");
return con;
}
private static byte[] writeObject(Object object) throws SQLException ...{
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
byte[] ab = null;
try ...{
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
ab = baos.toByteArray();
} catch (IOException ex) ...{
ex.printStackTrace();
} finally ...{
try ...{
if (oos != null)
oos.close();
if (baos != null)
baos.close();
} catch (IOException e) ...{
e.printStackTrace();
}
}
return ab;
}
/**//* * 在上下文中的流中读取对象~~~ */
public static Object readObject(InputStream inputStream) throws Exception ...{
Object o = null;
ObjectInputStream ois = null;
try ...{
ois = new ObjectInputStream(inputStream);
o = ois.readObject();
} catch (Exception ex) ...{
ex.printStackTrace();
} finally ...{
if (ois != null)
ois.close();
}
return o;
}
/**//* * 根据不同的method,从流中读取或写入数据对象。 */
public static Object parseObject(Object obj1, String httpUrl, String method) ...{
Object obj2 = null;
URLConnection con = null;
DataOutputStream dataout = null;
byte[] buf = null;
try ...{
con = getCon(httpUrl, method);
} catch (Exception e) ...{
e.printStackTrace();
} /**//* 写入数据 */
if (obj1 != null) ...{
try ...{
dataout = new DataOutputStream(con.getOutputStream());
} catch (IOException e) ...{
e.printStackTrace();
}
try ...{
buf = writeObject(obj1); // 转换成字节数组
} catch (SQLException e) ...{
e.printStackTrace();
}
try ...{
dataout.write(buf); // 写入流中
} catch (IOException e) ...{
e.printStackTrace();
} finally ...{
try ...{
if (dataout != null) ...{
dataout.flush();
dataout.close();
}
} catch (IOException e) ...{
e.printStackTrace();
}
}
}
/**//* 读取数据 */
DataInputStream in = null;
try ...{
in = new DataInputStream(con.getInputStream());
} catch (IOException e) ...{
e.printStackTrace();
}
try ...{
obj2 = readObject(in);// 从流中读取对象~~~
} catch (Exception e) ...{
e.printStackTrace();
} finally ...{
if (in != null)
try ...{
in.close();
} catch (IOException e) ...{
e.printStackTrace();
}
}
return obj2;
}
/**//*
* 把对象转换成字节数组,保存在上下文的流中。
*/
public static void writeObject(OutputStream outputStream, Object object)
throws SQLException ...{
ByteArrayOutputStream baos = null;
ObjectOutputStream oos = null;
try ...{
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] ab = baos.toByteArray();
outputStream.write(ab);
} catch (IOException ex) ...{
ex.printStackTrace();
} finally ...{
try ...{
if (oos != null)
oos.close();
if (baos != null)
baos.close();
} catch (IOException e) ...{
e.printStackTrace();
}
}
}
//读取文件内容
public static String readFile(File file) throws Exception ...{
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(file)));
String aa = "";
StringBuffer tmp = new StringBuffer();
while (aa != null) ...{
aa = br.readLine();
if (aa != null)
tmp.append(aa + " ");
}
return tmp.toString();
}
//获得文件路径与文件内容的映射,递归实现。
public Map readFiles(Map map, File file, int urllen) throws Exception ...{
String keypath = "";
if (file.isDirectory()) ...{
File files[] = file.listFiles(new FilenameFilter() ...{//过滤允许的文件
public boolean accept(File dir, String name) ...{
if (name.endsWith("raq") || name.endsWith("rpt")
|| name.endsWith("jpg") || dir.isDirectory())
return true;
return false;
}
});
for (int i = 0; i < files.length; i++) ...{
readFiles(map, files[i], urllen);
}
} else ...{
String content = UpDownLoadUtil.readFile(file);
keypath = file.getPath().substring(urllen - 1);
map.put(keypath, content);
}
return map;
}
//写文件
public static void writeFile(String allPath, String content) ...{
FileOutputStream fileout = null;
PrintWriter out = null;
try ...{
int lastSplit=allPath.lastIndexOf("/");
if(lastSplit==-1)...{
lastSplit=allPath.lastIndexOf("/");
}
String folderName = allPath.substring(0, lastSplit);
File path = new File(folderName);
if (!path.exists()) ...{
path.mkdirs();
}
File file = new File(allPath);
if (!file.exists()) ...{
file.createNewFile();
}
fileout = new FileOutputStream(file);
out = new PrintWriter(fileout);
out.println(content);
out.flush();
} catch (IOException e) ...{
e.printStackTrace();
} catch (Exception e) ...{
e.printStackTrace();
} finally ...{
try ...{
out.close();
fileout.close();
} catch (IOException e) ...{
e.printStackTrace();
}
}
}
}
2编写上传和下载的SERVLET类。这个不能用init方法,因为添加这个方法会使servlet默认调用doGet方法。这里必须是doPost方法,因为通过post提交,才能传递序列化的对象。
public class UpServlet extends HttpServlet {
// private ServletConfig config;//
//
// public void init(ServletConfig config) throws ServletException {// // super.init(config);
// this.config = config;
// }
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException {
try {
Map filesMap = (Map) UpDownLoadUtil
.readObject(req.getInputStream());
String url = req.getSession().getServletContext().getRealPath("/");
Iterator iterator = filesMap.keySet().iterator();
while (iterator.hasNext()) {
String filepath = (String) iterator.next();
String allPath = url + "//report//" + filepath;// 只能上传report下面。
UpDownLoadUtil.writeFile(allPath, (String) filesMap
.get(filepath));
}
UpDownLoadUtil.writeObject(res.getOutputStream(), "成功上传!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class DownServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException {
String downfiles = null;
try {
downfiles = (String) UpDownLoadUtil
.readObject(req.getInputStream());
String url = req.getSession().getServletContext().getRealPath("/");
File file = new File(url + "//report//" + downfiles);// 只能下载report下面的文件。
Map map = new HashMap();
map = UpDownLoadUtil.readFiles(map, file, (url + "//report//")
.length());
UpDownLoadUtil.writeObject(res.getOutputStream(), map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
3编写WEB.XML文件。
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>reportdes</display-name>
<servlet>
<servlet-name>downServlet</servlet-name>
<servlet-class>com.servlet.DownServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>upServlet</servlet-name>
<servlet-class>com.servlet.UpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>downServlet</servlet-name>
<url-pattern>/downServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>upServlet</servlet-name>
<url-pattern>/upServlet</url-pattern>
</servlet-mapping>
</web-app>
4在客户端实现
下载到本地的实现方式(提供多文件下载):
Map map = (Map) UpDownLoadUtil.parseObject(remoteFolder
.getText(), remoteURL.getText(), "/downServlet");
if (map != null) {
Iterator iterator = map.keySet().iterator();
while (iterator.hasNext()) {
String filepath = (String) iterator.next();
String allPath = localFolder.getText() + "//"
+ filepath;
UpDownLoadUtil.writeFile(allPath, (String) map
.get(filepath));
}
}
上传到服务器,可实现了多个文件上传
Map fileMap = new HashMap();
try {
fileMap.put(dialog.getRemoteFolderValue() + "//"
+ item.getFilepath(), UpDownLoadUtil.readFile(new File(
selectFilePath)));
} catch (Exception e) {
e.printStackTrace();
}
// 客户端访问服务器端,指定servlet对应的URL
Object files = UpDownLoadUtil.parseObject(fileMap, dialog
.getRemoteURLValue(), "/upServlet");
System.out.println(files);