需要两个jar包
commons-fileupload-1.4.jar
commons-io-2.7.jar
upload
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("UTF-8");
//1 先判断上传的数据是否多段数据
if(ServletFileUpload.isMultipartContent(req)){
//创建FileItemFactory工厂实现类
FileItemFactory fileItemFactory = new DiskFileItemFactory();
//创建用于解析上传数据的工具类ServletFileUpload
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
//解析上传的数据,得到每一个表单项FileItem
try {
List<FileItem> fileItems = servletFileUpload.parseRequest(req);
for (FileItem f:fileItems
) {
if(f.isFormField()){
//普通表单项
System.out.println("表单项的name属性值"+f.getFieldName());
System.out.println("表单项的value属性值"+f.getString("UTF-8"));
}else{
//上传的文件
System.out.println("表单项的name属性值"+f.getFieldName());
System.out.println("上传的文件名"+f.getName());
f.write(new File("E:\\upload\\firstweb\\"+f.getName()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
download
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取要下载的文件名
String downloadFileName = "1.jpg";
//读取要下载的文件内容
ServletContext servletContext = getServletContext();
//获取要下载的文件类型
String mimeType = servletContext.getMimeType("/file/" + downloadFileName);
//通过响应头告诉客户端返回的数据类型
resp.setContentType(mimeType);
//告诉客户端收到的数据用于下载
//Content-Disposition 表示收到的数据怎么处理
//attachment 表示附件,需要下载使用
//filename 表示要下载的文件
resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(downloadFileName,"UTF-8"));
InputStream resourceAsStream = servletContext.getResourceAsStream("/file/" + downloadFileName);
//获取响应的输出流
OutputStream outputStream = resp.getOutputStream();
//将输入流复制给输出流 回传给客户端
IOUtils.copy(resourceAsStream,outputStream);
}
PREVIOUSCookie和Session
NEXTFilter