Servlet文件上传
文件上传:将本地文件,通过IO写入到服务器中。
三要素:
- 表单提交的方式必须是POST(GET方式上传有大小的限制)
- 表单中必须有文件上传表单项,且必须有name属性
- 表单必须有enctype属性,且必须是
enctype="multipart/form-data"
文件上传原理:表单提交时HTTP头部的 Content-Type 会有一个boundary分隔符,分隔符会分割表单提交的每项内容(也就是每个input域)
FileUpload简介
- DiskFileItemFactory 磁盘文件项工厂
- ServletFileUpload 核心解析类
- FileItem 文件项(解析后每个部分)
文件上传代码实现
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.创建磁盘文件项工厂
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// 2.创建核心解析类
ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
// 3.解析请求对象,将请求分成几个部分(FileItem)
try {
List<FileItem> list= fileUpload.parseRequest(request);
// 4.遍历集合获得每个部分的对象
for(FileItem fileItem:list){
// 判断是普通项还是文件上传项
if(fileItem.isFormField()){
// 普通项
// 获得普通项的名称:
String name = fileItem.getFieldName();
// 获得普通项的值:
String value = fileItem.getString("UTF-8");
}else{
// 文件上传项
// 获得文件的名称:
String fileName = fileItem.getName();
// 获得文件的输入流:
InputStream is = fileItem.getInputStream();
// 将文件写入到服务器的某个路径:
String path = getServletContext().getRealPath("/upload");
System.out.println(path);
// 创建输出流:
OutputStream os = new FileOutputStream(path+"\"+fileName);
int len = 0;
byte[] b = new byte[1024];
while((len = is.read(b))!=-1){
os.write(b, 0, len);
}
is.close();
os.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}