文件上传的组件用的是 Commons FileUpload
引入 commons-io-2.0.jar 和 commons-fileupload-1.2.1.jar
面Servlert:
上传的方法:
private void addTongGao(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
TongGaoDAO dao = new TongGaoDAOjdbc();
HttpSession session = request.getSession();
response.setCharacterEncoding("text/html;charset=UTF-8");
String message = "";
Map<String, String> mapFormValue = new HashMap<String,String>();
// List<File> files = new Vector<File>();
List<FileUpload> files = new Vector<FileUpload>();
DiskFileItemFactory factory = new DiskFileItemFactory();
String pathyin = "upload/temp";
String tempdir =this.getServletContext().getRealPath("/" + pathyin);
File d = new File(tempdir);
if(!d.exists()) {
d.mkdirs();
}
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
//读取表单中一般属性的值
byte[] bytes = new byte[(int) item.getSize()];
InputStream in = item.getInputStream();
in.read(bytes);
String name = item.getFieldName();
String value = new String(bytes,"UTF-8");
mapFormValue.put(name, value);
in.close();
bytes = null;
} else{
try {
if(item.getName() != null && !item.getName().equals("")) {
File fullFile = new File(item.getName());
File savedFile = new File(tempdir, fullFile.getName());
item.write(savedFile);
String name = savedFile.getName();
String url = pathyin + "/" + name;
String filepath = savedFile.getPath();
FileUpload fu = new FileUpload(name, url, filepath);
files.add(fu);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
String title = mapFormValue.get("title");
int count = dao.getCountTitle(title);
if(count > 0) {
message = "标题不能重复,改标题已存在,请重新填写。";
} else {
String category = mapFormValue.get("category");
String department = mapFormValue.get("department");
String enddate = mapFormValue.get("enddate");
String top = mapFormValue.get("top");
String text = mapFormValue.get("text");
String issuedate = StringUtil.changeDateTime(new java.util.Date(), "yyyy-MM-dd");
String publisher = ((Admin)session.getAttribute("jwgl.admin.user")).getUserid();
if(StringUtil.validateNull(title)) {
message = "标题不能为空,请填写标题!";
} else if(StringUtil.validateNull(category)) {
message = "类别不能为空,请选择类别!";
} else if(StringUtil.validateNull(department)) {
message = "发布部门不能为空,请填写发布部门!";
} else if(StringUtil.validateNull(text)) {
message = "内容不能为空,请填写内容!";
} else {
TongGao tg = new TongGao();
tg.setTitle(title);
tg.setText(text);
tg.setCategory(category);
tg.setDepartment(department);
tg.setPublisher(publisher);
tg.setIssuedate(issuedate);
tg.setEnddate(enddate);
tg.setTop(top);
tg.setFiles(files);
boolean flag = dao.addTongGao(tg);
if(flag) {
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"+"admin/TongGaoServlet?type=one&title=";
request.setAttribute("tg", tg);
message = "通告添加成功!<a href=\"javascript:void(window.location.href(\'"+basePath+"\' + encodeURI(\'"+tg.getTitle()+"\',\'UTF-8\')))\">查看该公告 </a>";
} else {
message = "通告添加失败,请重新添加!";
}
}
}
下载的方法:
public void downLoad(String filePath,HttpServletResponse response,HttpServletRequest request,boolean isOnLine)
throws Exception{
File f = new File(filePath);
if(!f.exists()){
String message = "文件为找到,可能被其他用户删掉。";
request.setAttribute("message", message);
request.getRequestDispatcher("/error.jsp").forward(request, response);
// response.sendError(404,"File not found!");
// return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
response.reset(); //非常重要
if(isOnLine){ //在线打开方式
URL u = new URL("file:///"+filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename="+f.getName());
//文件名应该编码成UTF-8
}
else{ //纯下载方式
response.setContentType("application/x-msdownload");
System.out.println(f.getName());
response.setHeader("Content-Disposition", "p_w_upload; filename=" + java.net.URLEncoder.encode(f.getName(), "UTF-8"));
}
OutputStream out = response.getOutputStream();
while((len = br.read(buf)) >0)
out.write(buf,0,len);
br.close();
out.close();
}
这是通过流的方式下载(这样以什么后缀结尾的文件都可以下载)
下载还可以通过连接下载:当前项目的访问路劲+下载文件的相对路劲 (但是这种要是下载jpg 等其他后缀的文件如果不配置则直接打开)
删除文件:
private boolean deleteFiles(List<FileUpload> files, String servletpath) {
boolean deletefileflag = false;
if(files != null && files.size() != 0) {
for(int i=0;i<files.size();i++) {
String path = servletpath + files.get(i).getUrl().replaceAll("/", "\\\\");
File f = new File(path);
f.delete();
}
deletefileflag = true;
} else {
deletefileflag = true;
}
return deletefileflag;
}
这个很简单,先获得路径,然后new,然后delete
form表单中增加:
enctype="multipart/form-data"