我有一个jsp表格,接受有关员工姓名,性别,年龄,电子邮件地址和
Servlet 3.0 容器对多部分数据有标准支持。首先,您应该编写一个 HTML 页面,该页面将文件输入与其他输入参数一起获取。
<form action="uploadservlet" method="post" enctype="multipart/form-data">
<input type="text" name="name" />
<input type="text" name="age" />
<input type="file" name="photo" />
<input type="submit" />
</form>
现在编写一个使用 Servlet 3.0 Upload API 的 UploadServlet。下面是演示 API 用法的代码。首先,处理多部分数据的 servlet 应该使用以下两种方法中的任何一种来定义 MultiPartConfig:
-
@MultiPartConfig
Servlet 类的注释 web.xml,
通过在定义中添加<multipart-config>
条目<servlet>
。
这是 UploadServlet,
@MultipartConfig
public class UploadServlet extends HttpServlet
{
protected void service(HttpServletRequest request,
HttpServletResponse responst) throws ServletException, IOException
{
Collection<Part> parts = request.getParts();
if (parts.size() != 3) {
//can write error page saying all details are not entered
}
Part filePart = httpServletRequest.getPart("photo");
InputStream imageInputStream = filePart.getInputStream();
//read imageInputStream
filePart.write("somefiepath");
//can also write the photo to local storage
//Read Name, String Type
Part namePart = request.getPart("name");
if(namePart.getSize() > 20){
//write name cannot exceed 20 chars
}
//use nameInputStream if required
InputStream nameInputStream = namePart.getInputStream();
//name , String type can also obtained using Request parameter
String nameParameter = request.getParameter("name");
//Similialrly can read age properties
Part agePart = request.getPart("age");
int ageParameter = Integer.parseInt(request.getParameter("age"));
}
}
如果您没有使用Sevlet 3.0容器,则应调整Apache Commons File Upload。以下是使用Apache Commons File Upload的链接:
- 使用 Apache Commons 文件上传
- Apache 共享资源文件上传示例
引用:
- Servlet 3.0 javax.servlet.http.HttpServletRequest API
- Servlet 3.0 javax.servlet.http.Part API
- 使用 Servlet 3.0 上传文件