我有一个jsp表单,其中包含有关员工姓名,性别,年龄,电子邮件地址和a的详细信息
答案 0 :(得分:2)
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上传API的UploadServlet。以下是演示API用法的代码。解决servlet处理多部分数据应该使用以下两种方法中的任何一种来定义MultiPartConfig:
@MultiPartConfig
注释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文件上传的链接:
<强>参考文献:强>