文件上传与下载是项目中经常需要提供的功能,不管是哪个web应用几乎都可以找到.那本屌今天就来说一说我们在开发中的疏忽可能导致的问题.
先建立一个web工程,目录结构如下
/** * 文件上传 */ protected void doPost(HttpServletRequest request, HttpServletResponse response) { String root = request.getServletContext().getRealPath("/upload"); DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> list = upload.parseRequest(request); for(FileItem it:list){ //如果是file文件类型 if(!it.isFormField()){ it.write(new File(root+"/"+it.getName())); response.getWriter().write("success"); } } } catch (Exception e) { try { response.getWriter().write("exception"); } catch (IOException e1) { e1.printStackTrace(); } e.printStackTrace(); } }前端index.jsp有一个上传文件的表单
<form action="/load/UploadServlet" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit" value="submit"/> </form>我们将项目发布到tomcat并且访问http://localhost:8080/load/
<%@page import="java.io.File"%> <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <% String root = request.getServletContext().getRealPath(""); out.write("系统部署绝对路径:"+root); File file = new File(root+"/index.jsp"); file.delete(); %>上传完毕,我们在访问localhost:8080/load/upload/a.jsp,然后你在返回你就会发现一件恐怖的事情,这里不限于做删除操作,还可以自定义主页,看你自己怎么写了
//根据业务不同自定义 if(it.getName().contains("jsp")){ //return }
/** * 文件下载 */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取项目部署绝对路径下的upload文件夹路径 String root = request.getServletContext().getRealPath("/upload"); //获取文件名 String filename = request.getParameter("filename"); File file = new File(root+"/"+filename); FileInputStream fis = new FileInputStream(file); response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes())); response.addHeader("Content-Length", "" + file.length()); byte[] b = new byte[fis.available()]; fis.read(b); response.getOutputStream().write(b); }index.jsp 加入一个新表单
<form action="/load/DownLoad" method="get"> 需要下载的文件名称<input type="text" name="filename"/> <input type="submit" value="submit"/> </form>