文件的上传和下载实例:
文件的上传:
编写UpFile.java文件:这个文件的主要完成上传文件。
packageupfile.file;
public classUpFile extends HttpServlet {
protected void doGet(HttpServletRequestreq, HttpServletResponse resp)
throws ServletException,IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequestrequest, HttpServletResponse response)
throws ServletException,IOException {
try {
PrintWriter out =response.getWriter();
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory =new DiskFileItemFactory();
ServletFileUpload upload = newServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
List<FileItem> list =upload.parseRequest(request);
for(FileItem item:list){
if(item.isFormField()){
String paramN= item.getFieldName();
String paramV= item.getString("UTF-8");
out.write(paramN+"="+paramV);
}else{
StringfileName = item.getName();
fileName =fileName.substring(fileName.lastIndexOf("\\")+1);
System.out.println("fileName= "+fileName);
if(!fileName.equals("")&&fileName!=null){
StringuuidName = refactory(fileName);
StringbasePath = this.getServletContext().getRealPath("/WEB-INF/newFile");
StringfinalPath = realPath(basePath,uuidName);
System.out.println("finalPath= "+finalPath);
InputStreamin = item.getInputStream();
File file= new File(finalPath);
OutputStreamoutFile = new FileOutputStream(file);
bytebuffer[] = new byte[1024];
while(in.read(buffer)>0){
outFile.write(buffer);
}
outFile.flush();
outFile.close();
in.close();
request.setAttribute("msg","上传成功");
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
request.setAttribute("msg","上传失败了");
}
request.getRequestDispatcher("msg.jsp").forward(request,response);
}
private String realPath(String basePath,String uuidName) {
int HC = uuidName.hashCode();
int bir1 = HC & 0xf;
int bir2 = HC>>4 & 0xf;
String filePath =basePath+"\\"+bir1+"\\"+bir2+"\\";
File file = new File(filePath);
if(!file.exists()){
file.mkdirs();
}
return filePath+uuidName;
}
private String refactory(String fileName){
System.out.println("uuidName ="+UUID.randomUUID().toString()+"_"+fileName);
returnUUID.randomUUID().toString()+"_"+fileName;
}
}
编写index.jsp文件:jsp页面显示用户要上传的文件;
<form action="${pageContext.request.contextPath}/upfile" enctype="multipart/form-data" method="post">
上传文件:<input type="file"name="file"><br>
<inputtype="submit" value="上传">
编写ListFile.java文件:列出要下载的文件
package listfile.list;
public classListFile extends HttpServlet {
protected void doGet(HttpServletRequestreq, HttpServletResponse resp)
throws ServletException,IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequestrequest, HttpServletResponse response)
throws ServletException,IOException {
request.setCharacterEncoding("UTF-8");
String filePath =this.getServletContext().getRealPath("/WEB-INF/newFile");
Map map = new HashMap();
traverse(new File(filePath),map);
request.setAttribute("map",map);
System.out.println("map ="+map);
request.getRequestDispatcher("/ListFile.jsp").forward(request,response);
}
private void traverse(File file, Map map){
if(file.isFile()){
String fileName =file.getName();
String realName =fileName.substring(fileName.indexOf("_")+1);
map.put(fileName, realName);
}else{
File files[] =file.listFiles();
for(File f:files){
traverse(f,map);
}
}
}
}
编写listFile.jsp文件:显示前台页面。
<c:forEach var="fileName"items="${map }">
<c:url var="path" value="/downfile">
<c:param name="uuidName">${fileName.key}</c:param>
<c:param name="realName">${fileName.value}</c:param>
</c:url>
文件名:${fileName.value }
<a href="${path }">下载</a><br>
</c:forEach>
编写下载文件DownFile.java。下载文件:
packagedownfile.down;
public classDownFile extends HttpServlet {
protected void doGet(HttpServletRequestreq, HttpServletResponse resp)
throws ServletException,IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequestrequest, HttpServletResponse response)
throws ServletException,IOException {
request.setCharacterEncoding("UTF-8");
String uuidName =request.getParameter("uuidName");
String realName =request.getParameter("realName");
realName = newString(realName.getBytes("ISO8859-1"),"UTF-8");
uuidName = newString(uuidName.getBytes("ISO8859-1"),"UTF-8");
System.out.println(uuidName+" ="+realName);
File fileName = newFile(getFileName(uuidName));
if(!fileName.exists()){
request.setAttribute("msg","不存在文件");
}else{
response.setHeader("content-disposition","attachment;filname="+realName);
FileInputStream in = newFileInputStream(fileName);
OutputStream out =response.getOutputStream();
byte buffer[] = new byte[1024];
while(in.read(buffer)>0){
out.write(buffer);
}
out.flush();
out.close();
in.close();
}
}
private String getFileName(StringuuidName) {
int hashcode = uuidName.hashCode();
int dir1 = hashcode & 0xf;
int dir2 = hashcode>>4 &0xf;
System.out.println("dir1 ="+dir1+" dir2 = "+dir2);
String path =this.getServletContext().getRealPath("/WEB-INF/newFile")
+"\\"+dir1+"\\"+dir2+"\\"+uuidName;
return path;
}
}
说明:文件由上传后才能下载