1.文件上传
1.1前端代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="uploadtest" method="post" enctype="multipart/form-data">
名称:<input type="text" name="uname">
图片:<input type="file" name="pic">
<input type="submit" value="上传">
</form>
</body>
</html>
1.2java代码
@WebServlet(urlPatterns = "/uploadtest")
public class UpLoadTest 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 {
try {
//1.创建上传文件对象
SmartUpload smartUpload = new SmartUpload();
//2.初始化上传操作
/**
* 第一个参数:请求的servlet,在servlet中传this即可
* 第二个参数:servlet上挂起的当前请求
* 第三个参数:servlet上挂起的当前响应
* 第四个参数:请求JSP的错误页面的URL,或null
* 第五个参数:是否需要session
* 第六个参数:以字节为单位的缓冲区大小
* 第七个参数:缓冲区应该在缓冲区溢出时自动刷新到输出流,还是抛出IOException
*/
PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this,req,resp,null,false,1024,true);
smartUpload.initialize(pageContext);
//2.1设置编码
smartUpload.setCharset("utf-8");
//3上传
smartUpload.upload();
//4.获取文件信息
File file = smartUpload.getFiles().getFile(0);
String filename = file.getFileName();
String type = file.getContentType();
//获取文本信息,文件上传时,用户添加的信息(和之前的获取操作不一致)
String uname = smartUpload.getRequest().getParameter("uname");
System.out.println(uname);
//5.指定上传路径(在项目里新建一个uploadfiles文件夹,在文件夹里新建一个.txt文件,不然无法上传)
String filePath = "/uploadfiles/"+filename;
file.saveAs(filePath,File.SAVEAS_VIRTUAL);
req.setAttribute("filename",filename);
//跳转至success.jsp页面
req.getRequestDispatcher("success.jsp").forward(req,resp);
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
}
一定要建这个文件夹,并且在他的目录下再建一个文件,不然寻找不到路径
2.文件下载
2.1前端代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="downimg?filename=${filename}">下载</a>
<img src="uploadfiles/${filename}">
</body>
</html>
2.2java代码
@WebServlet(urlPatterns = "/downimg")
public class DownLoadTest 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"+URLEncoder.encode(filename,"UTF-8"));
//跳转页面
req.getRequestDispatcher(path).forward(req,resp);
//清空缓冲区
resp.flushBuffer();
}
}