前提要求
前端页面要求
method=“post”
enctype=“multipart/form-data”
上传文件的input的type=“file”
每个上传的组件必须有name属性,这样后台才能获取到数据
<form action="/UploadServlet" method="post" enctype="multipart/form-data">
上传文件所要用到的类、接口和方法
由于我们上传文件到本地服务器,需要解析请求到tomcat服务器的内容,然后写入本地目标文件夹,我们手工操作,会花费大量的时间精力,可能还会因为一个标点符号或者其他出错。所以为了方便我们使用apache上传文件的组件:需要导入两个第三方包
下载地址:Apache官网–project–commons–FileUpload
api:下载的jar包中打开index.html(必须在下载原目录打开,我的默认C:\Users\Administrator\Downloads)
1.Apache-fileupload.jar – 文件上传核心包
2.Apache-commons-io.jar
ServletFileUpload类
主要用来解析request对象
常用方法
1、boolean isMultipartContent(HttpServletRequest req)
作用:determines whether the request contains multipart content.
3、**List parseRequest(HttpServletRequest req)throws FileUploadException
作用:解析request,结合DiskFileItemFactory,最终将form表单中的每个input标签解析成一个一个的FileItem对象,存储在List集合中
FileItemFactory接口
实现类
public DiskFileItemFactory()
作用:主要将form表单中的每个input标签解析成一个一个的FileItem对象
FileItem接口
常用方法
1、boolean isFormField()
作用:判断是不是普通表单
2、 getFieldName()
作用:Returns the name of the field in the multipart form corresponding to this file item.
(表单字段name属性值)
3、 getName()
作用:Returns the original filename in the client’s filesystem, as provided by the browser (or other client software).(文件上传字段文件名)
4、getString()
作用:Returns the contents of the file item as a String, using the default character encoding.
5、getString(String encoding)
作用:Returns the contents of the file item as a String, using the specified encoding.
6、write(File file)
作用:A convenience method to write an uploaded item to disk.
Servlet代码
{
//设置编码格式,
//普通的form,并且使用的post提交的数据编码有效
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
/**
* 准备上传所要用到的类
* DiskFileItemFactory,负责管理磁盘文件
* ServletFileUpload,负责上传和解析文件
*/
//判断表单enctype属性是否为 multipart/form-data,
boolean multipartContent = ServletFileUpload.isMultipartContent(request);
if(!multipartContent){
//若不是,抛异常,也可以给用户输出提示
throw new RuntimeException("The form's enctype attribute value must be multipart/form-data");
}
//创建保存文件的路径
//若是,得到form表单中的每个input组件(FileItem对象)
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
//解析
try {
List<FileItem> list = upload.parseRequest(request);
//遍历每一个FileItem
for (FileItem m:list
) {
//判断它是不是普通组件
if(m.isFormField()){
//如果是普通组件,就输出name属性值
String name = m.getFieldName();
System.out.println("name="+name);
//得到value值,用重载的getString()方法解决编码
String value = m.getString("UTF-8");
System.out.println("value="+value);
}else {
//如果是file类型组件,得到文件名
String fileName = m.getName();
System.out.println("文件名="+fileName);
//保存进指定文件
m.write(new File("E:\\"+fileName));
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}