采用springmvc架构,只贴出关键代码,其他一概论之。
上传:
jsp页面
<form action="${pageContext.request.contextPath}/UploadHandleServlet" method="post" enctype="multipart/form-data"> 上传用户x:<input type="text" name="username"><br/> 上传文件1:<input type="file" name="file1"><br/> <input type="submit" value="提交"> </form>
后台代码
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss"); String savePath =request.getSession().getServletContext().getRealPath("/WEB-INF/upload"); File file = new File(savePath); if (!file.exists()) { file.mkdir(); } String message =""; try{ DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024*100); factory.setRepository(file); ServletFileUpload upload = new ServletFileUpload(factory); upload.setHeaderEncoding("UTF-8"); List<FileItem> list = upload.parseRequest(request); //正则匹配,过滤路径取文件名 String regExp = ".+\\\\(.+)$"; Pattern p = Pattern.compile(regExp); String fileName=""; for(FileItem item : list){ if(item.isFormField()){ String name = item.getFieldName(); String value = item.getString("UTF-8"); System.out.println(name + "=" + value); }else{ String name = item.getName(); name = name.substring(name.lastIndexOf("\\")+1); fileName = savePath+"/"+ sdf1.format(new Date()) + "_"+name; item.write(new File(fileName)); } } message = "文件上传成功!"; }catch (Exception e) { message= "文件上传失败!"; e.printStackTrace(); }
文件下载
//获得文件名和文件路径 String name = map.get("name")+""; String path = map.get("path")+""; String filename= new String(name.getBytes("utf-8"),"iso8859-1"); File file = new File(path); InputStream fis = new BufferedInputStream(new FileInputStream(path)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); response.reset(); response.addHeader("Content-Disposition", "attachment;filename=" + new String(name.replaceAll(" ", "").getBytes("utf-8"),"iso8859-1")); response.addHeader("Content-Length", "" + file.length()); OutputStream os = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); os.write(buffer);// 输出文件 os.flush(); os.close();
本文出自 “bulajunjun” 博客,请务必保留此出处http://5148737.blog.51cto.com/5138737/1774535
原文地址:http://5148737.blog.51cto.com/5138737/1774535