文件上传下载

blackdreamzg 2006-07-06 11:58:54
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;
}
...全文
227 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
cleansunshing 2006-07-06
  • 打赏
  • 举报
回复
mark
huxinsheng168 2006-07-06
  • 打赏
  • 举报
回复
up

62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧