1.需要的包SmartUpload.jar
2.上传
public void upLoad(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("html/text;charset=utf-8");
String path = request.getServletContext().getRealPath("/img");
File fl = new File(path);
if(fl.exists()){
fl.mkdir();
}
SmartUpload su = new SmartUpload();
try {
su.initialize(this.getServletConfig(), request, response);
su.upload();
int upcount = su.save(path);
String userage = su.getRequest().getParameter("userage");
String username = su.getRequest().getParameter("username");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
List list = new ArrayList();
File[] files =fl.listFiles();
for (int i = 0; i < files.length; i++) {
if(files[i].isDirectory())
continue;
list.add(files[i].getName());
}
request.setAttribute("filelist",list);
request.getRequestDispatcher("../downupload.jsp").forward(request, response);;
}
3.下载
public void downLoad(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("html/text;charset=utf-8");
String path = request.getServletContext().getRealPath("/img");
SmartUpload su = new SmartUpload();
su.initialize(this.getServletConfig(), request, response);
String filename = request.getParameter("filename").toString();
try {
su.downloadFile(path+"/"+filename);
} catch (SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
前台界面展示:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page isELIgnored="false"%>
<form method="POST" ENCTYPE="multipart/form-data" action="servlet/UpDownload?op=upLoad">
<input type="file" name="upfile"/>
<span>昵称:</span> <input type="text" name="username"/>
<span>年龄:</span> <input type="text" name="userage"/>
<input type="submit" value="上传">
</form>
-------------------<br>
<c:forEach items="${filelist }" var="item">
<a href="servlet/UpDownload?op=downLoad&filename=${item }"> <span>下载:${item }</span></a><br>
</c:forEach>
<!-- ----------------------------------------------------------------------------------- -->
<script>
function changeImg(img){
img.src = img.src+"&"+ new Date().toString();
}
</script>