需求准备:commons-fileupload,commons-io两个jar包
对于视图层:注意:form表单的method=“post” enctype=“multipart/form-data”
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'add.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
${requestScope.mess }
<form action="servlet/AddServlet" method="post" enctype="multipart/form-data" >
用户名:<input type="text" name="name"><br>
年龄:<input type="text" name="age"><br>
分数:<input type="text" name="score"><br>
照片:<input type="file" name="photo"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
控制层:
FileItem类的主要方法
isFormField():是否是file表单项,是file false,不是file true
getFieldName():表单项name的属性值
getString():对于非file表单项,value的属性值,对于file表单项,文件内容
getName():对于file表单项,是上传文件的名称,对于非file表单项,返回null
getContentType():对于file表单项,是指文件上传类型,非file表单项,返回null
getSize():对于file表单项,是指文件大小,非file表单项,是指name的长度
package com.bjsxt.servlet;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.bjsxt.entity.Student;
import com.bjsxt.service.StudentService;
import com.bjsxt.service.impl.StudentServiceImpl;
public class AddServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//创建FileItemFactory对象
FileItemFactory factory=new DiskFileItemFactory();
//ServletFileUpload对象
ServletFileUpload sfu=new ServletFileUpload(factory);
sfu.setHeaderEncoding("utf-8");
//设置文件的大小
sfu.setFileSizeMax(40*1024);//设置单个文件大小
sfu.setSizeMax(10*16*1024);//设置多个文件大小
//通过ServletFileUpload对象实现上传操作,将客户端一个个表单项封装到一个个FileItem中
List<FileItem> itemList=null;
try {
itemList= sfu.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
request.setAttribute("mess", "只能上传小于16kb的文件");
request.getRequestDispatcher("/add.jsp").forward(request, response);
return;
}
//遍历
String name=null;
int age=0;
double score=0;
String realName=null;
String photoName=null;
String photoType=null;
for (int i = 0; i < itemList.size(); i++) {
FileItem item = itemList.get(i);
String fieldName = item.getFieldName();
//普通表单项
if (item.isFormField()) {
//
if ("name".equals(fieldName)) {
name=item.getString("utf-8");
}
if ("age".equals(fieldName)) {
age=Integer.parseInt(item.getString());
}
if ("score".equals(fieldName)) {
score=Double.parseDouble(item.getString());
}
} else {
//文件表单项
if ("photo".equals(fieldName)) {
String contentType = item.getContentType();//images/jpg
photoType=item.getContentType();
if(!"image/jpeg".equals(contentType) && !"image/gif".equals(contentType)){
request.setAttribute("mess", "只能上传jpg和gif文件");
request.getRequestDispatcher("/add.jsp").forward(request, response);
return;
}
//创建文件上传路径(物理路径)
/*File dir=new File("C:\\apache-tomcat-7.0.69-windows-x64\\apache-tomcat-7.0.69\\webapps\\updownload1");*/
//由逻辑路径获得物理路径
String realPath = this.getServletContext().getRealPath("/upload");
File dir=new File(realPath);
//判断文件夹是否存在
if (!dir.exists()) {
dir.mkdir();
}
//指定上传的文件名
realName = item.getName();
String type = realName.substring(realName.lastIndexOf("."));
UUID uuid= UUID.randomUUID();
photoName=uuid.toString()+type;
//指定上传的文件夹和文件名
File file=new File(dir, photoName);
//上传文件到该位置
try {
item.write(file);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Student stu=new Student(name, age, score, realName, photoName, photoType);
StudentService stuService=new StudentServiceImpl();
int n=stuService.save(stu);
//页面跳转
if(n!=0){
//重定向:/后面要跟上下文路径 /stumgr /stumgr2
response.sendRedirect(request.getContextPath()+"/servlet/ShowAllServlet");
}else{
request.setAttribute("mess", "添加失败!");
request.getRequestDispatcher("/add.jsp").forward(request, response);
}
}
}
文件下载:
控制层:
package com.bjsxt.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import com.bjsxt.entity.Student;
import com.bjsxt.service.StudentService;
import com.bjsxt.service.impl.StudentServiceImpl;
public class DownloadServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse rep)
throws ServletException, IOException {
//接收信息
int id=Integer.parseInt(req.getParameter("idd"));
//创建服务层
StudentService stuService = new StudentServiceImpl();
Student stu=stuService.findById(id);
//进行读取下载操作
//创建输入流和输出流
String pathname=this.getServletContext().getRealPath("/upload")+"/"+stu.getPhotoName();
File file=new File(pathname);
rep.setContentLength((int)file.length());
rep.setContentType(stu.getPhotoType());
String header = req.getHeader("User-Agent").toLowerCase();
String realName = stu.getRealName();
if (header.indexOf("msie")>=0) {
realName=URLEncoder.encode(realName,"utf-8");
} else {
realName=new String(realName.getBytes("utf-8"),"iso-8859-1");
}
rep.setHeader("Content-disposition","attachment;fileName="+realName);
InputStream is=new FileInputStream(file);
OutputStream os=rep.getOutputStream();
//流操作
IOUtils.copy(is, os);
//关闭流
is.close();
os.close();
}
}
<body>
<!--输出所有的学生信息 -->
<a href="add.jsp">添加学生信息</a>
<table align="center" border="1" width="70%">
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>分数</th>
<th>照片</th>
<th>更新</th>
<th>删除</th>
</tr>
<c:forEach items="${requestScope.stuList2}" var="stu" >
<tr>
<td>${stu.id}</td>
<td>${stu.name }</td>
<td>${stu.age }</td>
<td>${stu.score}</td>
<td><img src="/upload/${stu.photoName }" alt="" /></td>
<td><a href="servlet/DownloadServlet?idd=${stu.id}">下载</a></td>
<td><a href="servlet/StudentServlet?idd=${stu.id}&method=delete">删除</a></td>
</tr>
</c:forEach>
</table>
</body>
这是最简单做web项目上传照片的一种简单方法,主要点在控制层,还有更高级的方法,就是利用vsftp以及nginx也是一种方法。
2900

被折叠的 条评论
为什么被折叠?



