<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="/day22/demo1" enctype="multipart/form-data" method="post">
用户名:<input type="text" name="username"><br>
文件:<input type="file" name="f"><br>
<input type="submit"><br>
</form>
</body>
</html>
package com;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
*文件上传
*/
public class Demo1Servlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*String username = request.getParameter("username");
String f=request.getParameter("f");
System.out.println(username);
System.out.println(f);*/
//创建磁盘文件项工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//创建核心上传对象
ServletFileUpload upload = new ServletFileUpload(factory);
//解析请求
try {
List<FileItem> list = upload.parseRequest(request);
//遍历list
for (FileItem fi : list) {
//判断是普通的上传组件还是文件上传组件
if(fi.isFormField()){
//普通的上传组件
//获取name属性
String name = fi.getFieldName();
//获取值
String string = fi.getString("utf-8");
System.out.println(name+"::"+string);
}else{
//文件上传组件
//获取name属性
String name = fi.getFieldName();
//获取文件的名称
String filename = fi.getName();
//获取文件内容
InputStream is = fi.getInputStream();
System.out.println("文件:"+name+"::"+filename+"::"+is);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}