public ActionForward upload(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm df = (DynaValidatorForm) form;
FormFile file = (FormFile) df.get("file");
String rootpath = "E:/tools/";
String saveDir = request.getParameter("saveDir");
if (saveDir != null && saveDir.length() > 0) {
rootpath += saveDir + file.getFileName();
} else {
rootpath += file.getFileName();
}
if (file != null && file.getFileSize() > 0) {
InputStream stream = file.getInputStream();
OutputStream bos = new FileOutputStream(rootpath);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead); }
bos.close();
stream.close();
}
response.sendRedirect("/test.do?method=listDir&dirname=" + saveDir);
return null;
}
=================================================================================
public ActionForward downLoad(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
try {
// String realpath = this.getServlet().getServletContext()
// .getRealPath("/upload/");
String realpath = "E:\\tools\\";
String filenamedownload = realpath + "\\"
+ request.getParameter("fileName");// 即将下载的文件的相对路径
String filenamedisplay = request.getParameter("fileName");// 下载文件时显示的文件保存名称
System.out.println(filenamedisplay); filenamedisplay = URLEncoder.encode(filenamedisplay, "UTF-8");
response.setContentType("application/x-download");// 设置为下载
response.addHeader("Content-Disposition", "attachment;filename="
+ filenamedisplay);
OutputStream output = null;
FileInputStream fis = null;
try {
output = response.getOutputStream();
fis = new FileInputStream(filenamedownload); byte[] b = new byte[1024];
int i = 0; while ((i = fis.read(b)) > 0) {
output.write(b, 0, i);
}
output.flush();
} catch (java.net.SocketException e) {
System.out.println("取消!");
} finally {
if (fis != null) {
fis.close();
fis = null;
}
if (output != null) {
output.close();
output = null;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}