文件上传就是讲本地磁盘文件 通过 IO 写入服务器的过程
文件上传的技术
- Servlet3.0
- JSPSmartUpload
- fileUpload
- 框架
文件上传3要素
- 表单的提交方式必须为post
- 表单中需要有文件上传表单项
- < input type = “file” name = “upload”>
- 表单的enctype属性的值需要是mutipart/form-data
文件上传原理分析
拿到请求,对请求进行解析,拿到分割线,使用分割线对内容进行切分
<h1>文件上传</h1>
<form action="${pageContext.request.contextPath }/UploadServlet" method="post" enctype="multipart/form-data">
<input type="text" name="name"><br/>
<input type="file" name="upload"><br/>
<input type="submit" value="上传">
</form>
FileUpload简介
API
DiskFileItemFactory:磁盘文件项工厂
ServletFileUpdate:核心解析类 返回值为一个集合
FileItem:文件项
@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(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");
System.out.println(name+" "+value);
}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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}