1.第一步:主页
上传下载<br/>
<form action="<c:url value='/Upload2Servlet'/>"
method="post"
enctype="multipart/form-data">
文件:<input type="file" name="txt"/><br/>
说明:<input type="text"name="desc"><br/>
<input type="submit"value="上传">
</form>
2.第二步:实现文件上传和下载
public class UploadServlet3 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory disk = newDiskFileItemFactory();// 声明临时路径
disk.setRepository(new File("f:/tm"));// 设置临时路径
ServletFileUpload sfu = newServletFileUpload(disk);// 声明解析request的核心类
try {
List<FileItem> files = sfu.parseRequest(request);// 解析request,每一个FileItem就是一个文件对象
Map<String,String> map = newHashMap<String, String>();
for (FileItem file : files){
if (file.isFormField()) {// 是一个简单值,即txt
String desc = file.getString("UTF-8");
System.err.println("描述为:" + desc);
map.put("desc", desc);
}else{
// 如果是文件就上传
String path = getServletContext().getRealPath("/up");// 获取文件保存目录
String fileName = file.getName();// 获取文件名
fileName= fileName
.substring(fileName.lastIndexOf("\\") + 1);
System.err.println("原文件名:" + fileName);
map.put("oldName",fileName);
// 改名
String uuid = UUID.randomUUID().toString().replace("-", "");
String exName = fileName.substring(fileName
.lastIndexOf(".") + 1);
String newName = uuid + "." + exName;
System.err.println("新文件名:" + newName);
map.put("newName",newName);
map.put("size", "" +file.getSize());// 文件大小
map.put("type",file.getContentType() + "");
// 使用工具类实现文件的copy
FileUtils.copyInputStreamToFile(file.getInputStream(),
new File(path + "/" + newName));
// 删除临时文件
file.delete();
}
}
// 放到request中去
request.setAttribute("map", map);
// 转发到显示页
request.getRequestDispatcher("/jsps/show.jsp").forward(request,
response);
}catch(FileUploadException e) {
e.printStackTrace();
}
}
}
3.显示页面
<body>
<p>以下是你上传的内容</p>
文件名:${map.oldName}<br/>
大小:${map.size }<br/>
类型: ${map.type }<br/>
说明: ${map.desc }<br/>
<c:choose>
<c:when test="${fn:startsWith(map.type,'image/') }">
<img width="500"height="800" src="<c:url value='/up/${map.newName }'/>"></img>
</c:when>
<c:otherwise>
<a href="<c:url value='up/${map.newName }'/>">下载</a>
</c:otherwise>
</c:choose>
</body>