附代码示例:
要填写的表单及文件代码如下
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传图片功能</title>
</head>
<body>
<form action="a.do" method="post" enctype="multipart/form-data">
<div align="center" >
<label>姓名: </label>
<input name="stuname" type="text"/>
<label>学号: </label>
<input name="stuno" type="text"/>
<label>年龄: </label>
<input name="age" type="text"/>
<label>电话号码: </label>
<input name="phone" type="text"/>
<br><br>
<label>性别: </label>
<input name="sex" type="radio" value="男" checked/> 男
<input name="sex" type="radio" value="女"/> 女<br><br>
<label>照片: </label>
<input name="picture" value="" type="file"/>
<br><br>
<input value="注册" type="submit"/>
</div>
</form>
</body>
</html>
Servlet接收参数和文件的代码如下:
package test;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
public class A extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("abc.jsp");
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 初始化
SmartUpload smartUpload = new SmartUpload();
ServletConfig config = this.getServletConfig();
smartUpload.initialize(config, request, response);
try {
// 上传文件
smartUpload.upload();
// 得到上传的文件对象
com.jspsmart.upload.File smartFile = smartUpload.getFiles().getFile(0);
String name = smartFile.getFileName();
// 保存文件
smartFile.saveAs("/picture/"+name, SmartUpload.SAVE_AUTO);
// 传过来的注册数据
// 只需要new SmartUpload().getRequest().getParameter(""))就能获取到相应的表单数据
String stuname = smartUpload.getRequest().getParameter("stuname");
int stuno = Integer.parseInt(smartUpload.getRequest().getParameter("stuno"));
System.out.println("name: "+stuname+" stuno: "+stuno);
response.sendRedirect("abc.jsp");
} catch (SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注意: 1.servlet代码去掉包名,换成自己的。
2.需要在自己的WebContent目录下创建picture文件。
3.导入smartupload.jar包