在实现文件上传和下载之前我们需要做一些准备工作,在Apache官网去下载文件上传下载的两个组件,下载链接这里给出:common-fileupload组件下载:
common-io组件下载:根据自己需求下载对应版本
一、创建工程
将所需要的两个开发包导入到工程项目中如图:
二、代码编写
1.前端页面代码
1). 在WebRoot目录下新建一个fileUpload.jsp页面,用来上传文件
1 <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP \'fileUpload.jsp\' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link type="text/css" href="http://www.likecs.com/styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <!-- 文件上传表单的提交方式必须是“post” 编码类型必须为:enctype="multipart/form-data" --> 27 <form action="UploadServlet" method="post" enctype="multipart/form-data"> 28 29 username: <input type="text" name="username" /><br> 30 file: <input type="file" name="file"><br> 31 file2: <input type="file" name="file2"><br> 32 <input type="submit" value="上传文件"> 33 34 </form> 35 36 </body> 37 </html>