1.导入smartupload.jar 包
2.准备上传页面
- form表单的标签中需要添加enctype属性
- 提交方式必须是post
<form method="post" action="/upload" enctype="multipart/form-data">
3.获取数据/保存文件
@WebServlet(value="/upload")
public class uploadServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.创建SmartUpload对象
SmartUpload smartUpload = new SmartUpload();
//2.初始化对象
PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this,req,resp,null,false,1024*5,true);
smartUpload.initialize(pageContext);
//3.设置编码方式
smartUpload.setCharset("utf-8");
//4.上传
try {
smartUpload.upload();
} catch (SmartUploadException e) {
e.printStackTrace();
}
//5.保存文件
File file =smartUpload.getFiles().getFile(0);
String fileName = file.getFileName();
String url = "uploadFiles/"+fileName;
try {
file.saveAs(url,File.SAVEAS_VIRTUAL);
} catch (SmartUploadException e) {
e.printStackTrace();
}
//6.展示上传文件
req.setAttribute("filename",fileName);
//7.获取表单中其他内容(当表单内有其他内容时,不能使用request获取,需要通过SmartUpload对象)
String username = smartUpload.getRequest().getParameter("uname");
//8.跳转页面
req.getRequestDispatcher("/show.jsp").forward(req,resp);
}
}
getPageContext()方法内7个参数
servlet: 请求的servlet,在servlet中传this即可
request: servlet上挂起的当前请求
response: servlet上挂起的当前响应
errorPageURL:请求JSP的错误页面的URL,或null
needsSSession:是否需要session(true/false)
buffer:以字节为单位的缓冲区大小
autoflush:缓冲区应该在缓冲区溢出时自动刷新到输出流,还是抛出IOException
文件下载
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>展示页面</title>
</head>
<body>
<h1>成功页面</h1>
<img src="uploadfiles/${fileName}">
<a href="download?fileName=${fileName}">下载</a>
</body>
</html>
@WebServlet("/download")
public class downloadServelet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String fileName = req.getParameter("fileName");
String path = "uploadfiles/"+fileName;
resp.setContentType("application/octet-stream");
resp.addHeader("Content-disposition","attachment;filename="+fileName);
req.getRequestDispatcher(path).forward(req,resp);
resp.flushBuffer();
}
}