导入两个jar包
前端
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="/Upload.do">
上传文件:<input type="file" name="file" id="file">
<input type="text" name="age" id="d1">
<input type="submit" value="文件上传">
</form>
<a href="/download?filename=13.jpg" name="13.jpg">13.jpg</a>
</body>
</html>
上传
@WebServlet("/Upload.do")
public class UpLoad extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置工厂的存储区域
DiskFileItemFactory diskFileItemFactory1 = new DiskFileItemFactory(10240, (File) this.getServletConfig().getServletContext().getAttribute("javax.servlet.context.tempdir"));
//创建文件上传处理器
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory1);
//解析请求
List list = null;
try {
list = servletFileUpload.parseRequest(req);
//获取集合的迭代器
Iterator<FileItem> iterator = list.iterator();
while (iterator.hasNext()) {
FileItem next = iterator.next();
//处理表单项
if (next.isFormField()) {
//普通表单项(比如密码,多选框)
} else {
//获取上传文件名字
String string = next.getName();
//一般上传服务器,都保存在固定的文件中
File file = new File("e:/Temp", string);
//next.write(file);
FileUtils.copyInputStreamToFile(next.getInputStream(),file);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
下载
@WebServlet("/download")
public class DownLoad extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取文件名字
String filename = req.getParameter("filename");
//设置响应头内容类型为下载,保存在本地
resp.setContentType("application/x-msdownload");
//设置响应头,让下载的过程由用户干涉,还可以保证文件名称
resp.addHeader("content-disposition","attachment;filename="+filename);
//获取服务器文件路径
File src=new File("e:/Temp",filename);
FileUtils.copyFile(src,resp.getOutputStream());
}
}