例 1、文件上传。
第一步、file.jsp
……
<body>
<form action="${pageContext.request.contextPath}/servlet/UpLoadServlet" method="post" enctype="multipart/form-data">
请选择要上传的文件:<input type="file" name="filePath"/><br/>
请输入文件名:<input type="text" name="fileName"><br/>
<input type="submit" value="上传">
</form>
……
第二步、UpLoadServlet .java
package cn.itcast.web;
import *;
public class UpLoadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//定义哪些后缀类型的文件能被接收
String[] allowedExt=new String[]{"doc","jpg","jpeg"};
//如果客户端的请求类型是enctype="multipart/form-data 返回为true
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
System.out.println("判断客户端请求类型是否是enctype=multipart/form-data:"+isMultipart);
if(isMultipart){
// DiskFileItemFactory是创建FileItem对象的工厂,在这个工厂类中可以配置内存缓冲区的大小和存 //放临时文件的目录。
DiskFileItemFactory factory = new DiskFileItemFactory();
//表示上传的文件存储在内存空间的大小,如果该内存空间存不下的情况下,会存储到硬盘的临时目录下
//即factory.setRepository(new File("D:/temp"));设置的文件目录
factory.setSizeThreshold(1024*1024);
factory.setRepository(new File("D:/temp"));
//ServletFileUpload负责处理上传的文件数据,并将每部分的数据封装到FileItem对象中
ServletFileUpload upload = new ServletFileUpload(factory);
try {
/********************************限制上传文件的大小***************************/
long MAXSIZE=1024*1024*1024;
//设置上传文件的大小(以字节为单位)
upload.setFileSizeMax(MAXSIZE);
//超过了的话会抛出FileSizeLimitExceededException的异常
/***********************************************************************************/
//解析request对象
List<FileItem> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
/*
* 把表单的组件<input>都看成一个FileItem
*/
FileItem item = (FileItem) iter.next();
//如果是表单域(除了type="file"),执行下面的if
if (item.isFormField()) {
// 请输入文件名:<input type="text" name="fileName" value="qq"><br/>
String name = item.getFieldName();//这里的name是指上面name的值,即
//fileName
String value = item.getString();//这里的value是指上面value的值,即
//qq
System.out.println("isFormField表单域中元素的:"+name+":"+value);
} else {
//如果是文件域(type="file"),执行下面的内容
//<input type="file" name="filePath"/><br/>
String fieldName = item.getFieldName(); //获取文件域中name的属性值
String fileName = item.getName(); //上传文件的全路径
String contentType = item.getContentType();//上传文件的类型
boolean isInMemory = item.isInMemory();//临时 true保存在内存中 false表示表示保存在硬盘上
long sizeInBytes = item.getSize(); //文件大小以字节为单位
System.out.println("!item.isFormField() fieldName文件域中的name属性值:"+fieldName);
System.out.println("!item.isFormField() fileName文件域中上传文件的全路径:"+fileName);
System.out.println("!item.isFormField()上传文件的类型:"+contentType);
System.out.println("!item.isFormField()文件临时保存的方式 true表示放在内存中:"+isInMemory);
System.out.println("!item.isFormField()上传文件的大小(字节):"+sizeInBytes);
/*******************************方法一***********************************************
//获取上传文件的名称:
String fileupdate_file_name=fileName.substring(fileName.lastIndexOf("\\")+1);
System.out.println("fileupdate_file_name:"+fileupdate_file_name);
File uploadFile=new File("D:/"+fileupdate_file_name);
item.write(uploadFile);
*******************************方法二***********************************************
//获取上传文件的名称:
File file=new File(fileName);
System.out.println("file.getName():"+file.getName());
File uploadFile=new File("D:/"+file.getName());
item.write(uploadFile);
************************************************************************************
//保存固定的文件名:
//定义一个file指向具体的文件
File uploadedFile = new File("D:/a.jpg");
//把上传的内容写到一个文件中
item.write(uploadedFile);
************************************************************************************/
//获取真实路径
String realPath=this.getServletContext().getRealPath("/pics");
String fileupdate_file_name=fileName.substring(fileName.lastIndexOf("\\")+1);
System.out.println("fileupdate_file_name:"+fileupdate_file_name);
//获取文件的后缀名
String fileupdate_file_name_end = fileName.substring(fileName.lastIndexOf(".")+1);
System.out.println("fileupdate_file_name_end:"+fileupdate_file_name_end);
//阻止某些类型的文件
if(fileupdate_file_name_end!=null){
boolean flag = Arrays.asList(allowedExt).contains(fileupdate_file_name_end);
if(!flag){
throw new RuntimeException("您上传的文件类型不系统不支持");
}
}
/************************************************************************************/
//上传的文件保存在pics文件夹中下
if(fileupdate_file_name!=null){
realPath=realPath+"\\"+fileupdate_file_name;
System.out.println("realPath:"+realPath);
}else{
realPath=realPath+"\\temp";
System.out.println("realPath:"+realPath);
}
File uploadFile=new File(realPath);
item.write(uploadFile);
//上传文件之后,打开路径C:\apache-tomcat-6.0.20\webapps\day19FileUpload\pics
//便可以看到上传的文件内容
/************************************************************************************/
}
}
}catch(FileSizeLimitExceededException e1){
throw new RuntimeException("您上传的文件的大小不能超过1G");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
第三步、readme.txt
1.关于上传的特殊说明:
* 设置上传文件的大小
* 获取文件的名称
方法一
方法二
*设置上传指定类型的文件
/
/定义哪些后缀类型的文件能被接收
String[] allowedExt=new String[]{"doc","jpg","jpeg"};
......
String fileupdate_file_name=fileName.substring(fileName.lastIndexOf("\\")+1);
System.out.println("fileupdate_file_name:"+fileupdate_file_name);
//获取文件的后缀名
String fileupdate_file_name_end = fileName.substring(fileName.lastIndexOf(".")+1);
System.out.println("fileupdate_file_name_end:"+fileupdate_file_name_end);
//阻止某些类型的文件
if(fileupdate_file_name_end!=null){
boolean flag = Arrays.asList(allowedExt).contains(fileupdate_file_name_end);
if(!flag){
throw new RuntimeException("您上传的文件类型不系统不支持");
}
}
第四步、执行,在IE中键入:http://localhost:8080/day19FileUpload/file.jsp 然后上传一个1.jpg 图片
打开:C:\apache-tomcat-6.0.20\webapps\day19FileUpload\pics 可以看到上传的图片。
MyEclipse中的执行结果:
判断客户端请求类型是否是enctype=multipart/form-data:true
!item.isFormField() fieldName文件域中的name属性值:filePath
!item.isFormField() fileName文件域中上传文件的全路径:1.jpg
!item.isFormField()上传文件的类型:image/pjpeg
!item.isFormField()文件临时保存的方式 true表示放在内存中:true
!item.isFormField()上传文件的大小(字节):71874
fileupdate_file_name:1.jpg
fileupdate_file_name_end:jpg
realPath:C:\apache-tomcat-6.0.20\webapps\day19FileUpload\pics\1.jpg
isFormField表单域中元素的:fileName:aaa
文件的下载
例2、文件的下载
Download.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<a href="${pageContext.request.contextPath}/pics/1.jpg">1.jpg下载</a><br/>
<a href="${pageContext.request.contextPath}/pics/src.zip">src.zip下载</a><br/>
在IE中键入:http://localhost:8080/day19FileUpload/download.jsp 即可实现下载
例3、隐藏下载文件的真实路径,增加安全性。
第一步、download2.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html;charset=UTF-8"%>
<a href="${pageContext.request.contextPath}/servlet/DownServlet?filename=src.zip">下载</a><br/>
<a href="${pageContext.request.contextPath}/servlet/DownServlet?filename=1.jpg">下载</a><br/>
第二步、DownServlet.java
package cn.itcast.web;
import *;
public class DownServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
//获取filename的值
String filename = request.getParameter("filename");
response.setCharacterEncoding("UTF-8");
/*web服务器需要告诉浏览器其输出的内容的类型不是普通的文本文件
* 而是一个要保存到本地的下载文件
* 设置Content-type的值为:application/x-msdownload
*/
//response.setHeader("Content-type", "application/x-msdownload");
response.setContentType("application/x-msdownload");
/*web服务器希望浏览器不直接处理相应的实体内容,而是由用户选择将相应的实体内容保存到一
* 个文件中,这需要设置Content-Disposition报头,该报头指定了接收程序处理数据内容的方
* 式 ,在HTTP应用中只有attachment是标准方式
* attachment表示要求用户干预
* 在attachement后面还可以指定filename参数
* 该参数是服务器建议浏览器将实体内容保存到文件中的文件名称。
* 在设置Content-Disposition之前,一定要指定Content-type
*/
response.setHeader("Content-Disposition", "attachment;filename="+filename);
//1.获取下载的文件 src.zip
String realPath = this.getServletContext().getRealPath("/pics");
realPath=realPath+"\\"+filename;
System.out.println(realPath);
//2.转化为输入流(读取文件到输入流)
FileInputStream fis=new FileInputStream(realPath);
BufferedInputStream bis=new BufferedInputStream(fis);
//3.定义输出流,从相应对象中获取输出流
OutputStream fos=response.getOutputStream();
BufferedOutputStream bos=new BufferedOutputStream(fos);
//4.从输入流中读取写入到输出流中
byte[] buf=new byte[200*1024];
int len=0;
while((len = bis.read(buf))!=-1){
bos.write(buf,0,len);
}
//5.关闭
bis.close();
bos.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
第三步、在IE中键入:http://localhost:8080/day19FileUpload/download2.jsp 即可看到效果
例4、下载中乱码问题:
问题演示:在例3基础上,添加 课表.jpg到文件夹pics中,然后将第一步中的download2.jsp增加一行:
<a href="${pageContext.request.contextPath}/servlet/DownServlet?filename=课表.jpg">下载</a><br/>将出现乱码问题,会抛出异常,服务器找不到路径,怎么解决?
……
request.setCharacterEncoding("UTF-8");
String filename= request.getParameter("filename");
filename=new String(filename.getBytes("iso8859-1"),"UTF-8");
System.out.println(filename);//课表.jsp
……
response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoding.encod(filename,”UTF-8”));
处理乱码方式等同于get
上传下载的案例
第一步、建表
CREATE TABLE userfile
(
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(12),
sex VARCHAR(4),
tel VARCHAR(11),
filepath VARCHAR(12),
filename VARCHAR(12)
)
第二步、user.jsp
……
<form action="${pageContext.request.contextPath}/servlet/UserUploadServlet" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"><br/>
性别:<input type="radio" name="sex" value="男" >男
<input type="radio" name="sex" value="女" checked="checked">女<br/>
电话:<input type="text" name="tel"><br/>
上传的文件:<input type="file" name="fileName"><br/>
<input type="submit" value="上传"/><br/>
</form>
<a href="${pageContext.request.contextPath}/servlet/UserListServlet">查看</a>
……
第三步、userList.jsp
……
<body>
用户信息查询:<br/>
<table border="1">
<tr>
<td>用户名</td>
<td>性别</td>
<td>电话</td>
<td>文件名称</td>
<td>下载</td>
</tr>
<c:forEach items="${list}" var="user">
<tr>
<td>${user.username}</td>
<td>${user.sex}</td>
<td>${user.tel}</td>
<td>${user.filename}</td>
<td>
<a href="${pageContext.request.contextPath}/servlet/DownloadServlet?filepath=${user.filepath}&filename=${user.filename}">下载</a>
</td>
……
第四步、UserUploadServlet.java
package cn.itcast.web;
import *;
public class UserUploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
/*
* 保存表单域的Map
* <input type="text" name="username">
* map.put("username","zhang");
* map.put("sex","男");
*/
Map<String,String> formMap=new HashMap<String,String>();
/*
* 保存文件域的Map
* <input type="file" name="fileName">
* map.put("filepath",文件的名称(不带路径));
*
*/
Map<String,String> fileMap=new HashMap<String,String>();
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
try {
List<FileItem> items=upload.parseRequest(request);
Iterator<FileItem> it=items.iterator();
while(it.hasNext()){
FileItem item=it.next();
if(item.isFormField()){//表单域
String fieldName=item.getFieldName();
//处理中文乱码问题
fieldName=new String(fieldName.getBytes("iso8859-1"),"UTF-8");
String fieldValue=item.getString();
fieldValue=new String(fieldValue.getBytes("iso8859-1"),"UTF-8");
formMap.put(fieldName, fieldValue);
}else{//文件域
String file_fieldName=item.getFieldName();
String fileName=item.getName();
//获取文件的名称
String save_fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
//获取保存文件的路径
String realPath=this.getServletContext().getRealPath("/user");
//组织文件的完整路径
if(save_fileName!=null){
realPath=realPath+"\\"+save_fileName;
File uploadFile=new File(realPath);
item.write(uploadFile);
}
fileMap.put("filename", save_fileName);
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//封装信息到javabean
User user=new User();
user.setUsername(formMap.get("username"));
user.setSex(formMap.get("sex"));
user.setTel(formMap.get("tel"));
user.setFilepath("/user");
user.setFilename(fileMap.get("filename"));
DaoUserImpl daoUserImpl=new DaoUserImpl();
daoUserImpl.saveUser(user);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
第五步、User.java
package cn.itcast.bean;
public class User {
private Integer id;
private String username;
private String sex;
private String tel;
private String filepath;
private String filename;
……
第六步、UserListServlet.java
package cn.itcast.web;
import *;
public class UserListServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
DaoUserImpl daoUserImpl=new DaoUserImpl();
List<User> list=daoUserImpl.findAllUser();
request.setAttribute("list", list);
request.getRequestDispatcher("/userList.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
第七步、DaoUserImpl.java
package cn.itcast.dao.impl;
import *;
public class DaoUserImpl {
public void saveUser(User user) {
DBManager dbManager=new DBManager();
Connection conn=dbManager.getConnection();
PreparedStatement pstatement=null;
//组织sql语句
String sql="insert into userfile(id,username,sex,tel,filepath,filename) values(null,?,?,?,?,?)";
try {
pstatement=conn.prepareStatement(sql);
pstatement.setString(1, user.getUsername());
pstatement.setString(2, user.getSex());
pstatement.setString(3, user.getTel());
pstatement.setString(4, user.getFilepath());
pstatement.setString(5, user.getFilename());
pstatement.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
dbManager.closeResource(conn, pstatement, null);
}
}
public List<User> findAllUser() {
DBManager dbManager=new DBManager();
Connection conn=dbManager.getConnection();
PreparedStatement pstatement=null;
ResultSet rs=null;
List<User> list=new ArrayList<User>();
//组织sql语句
String sql="select id,username,sex,tel,filepath,filename from userfile order by id";
try {
pstatement=conn.prepareStatement(sql);
rs = pstatement.executeQuery();
while(rs.next()){
User user=new User();
user.setId(rs.getInt(1));
user.setUsername(rs.getString(2));
user.setSex(rs.getString(3));
user.setTel(rs.getString(4));
user.setFilepath(rs.getString(5));
user.setFilename(rs.getString(6));
list.add(user);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
dbManager.closeResource(conn, pstatement, rs);
}
return list;
}
}
第八步、DownloadServlet.java
package cn.itcast.web;
import *;
public class DownloadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
//获取路径
String filepath=request.getParameter("filepath");
filepath=new String(filepath.getBytes("iso8859-1"),"UTF-8");
//获取文件名称
String filename=request.getParameter("filename");
filename=new String(filename.getBytes("iso8859-1"),"UTF-8");
//System.out.println(filename);
response.setContentType("application/x-msdownload");
//注意下面一行
response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode(filename, "UTF-8"));
//获取真实路径
String realPath=this.getServletContext().getRealPath(filepath);
realPath=realPath+"\\"+filename;
//输入流
FileInputStream fis=new FileInputStream(realPath);
BufferedInputStream bis=new BufferedInputStream(fis);
//输出流
OutputStream fos=response.getOutputStream();
BufferedOutputStream bos=new BufferedOutputStream(fos);
int len=0;
byte[] buf=new byte[1024*1024];
while((len=bis.read(buf))!=-1){
bos.write(buf,0,len);
}
bis.close();
bos.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
第九步、DBManager.java
package cn.itcast.util;
import *;
//数据库管理类
public class DBManager {
private String className="com.mysql.jdbc.Driver";
private String username="root";
private String password="root";
private String url="jdbc:mysql://localhost:3306/test";
//1.注册驱动
public DBManager(){
try {
Class.forName(className);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//2.获取连接
public Connection getConnection(){
Connection conn=null;
try {
conn=DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
//3.关闭资源
public void closeResource(Connection conn,Statement statement,ResultSet rs){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(statement!=null){
statement.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
第十步、运行并,观察结果