1.给你的web工程添加jspSmartUpload.jar
2.在servlet中使用:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gbk");
response.setCharacterEncoding("gbk");
SmartUpload smart = null;
String method = request.getParameter("method");
if (method == null || "".equals(method)) {
smart = new SmartUpload();
smart.initialize(super.getServletConfig(), request, response);
try {
smart.upload();// 上传准备
} catch (SmartUploadException e1) {
e1.printStackTrace();
}
method = smart.getRequest().getParameter("method");
}
if ("upload".equals(method)) {
try {
updoad(request, response, smart);
} catch (Exception e) {
e.printStackTrace();
}
} else if ("list".equals(method)) {
list(request, response);
} else if ("delete".equals(method)) {
delete(request, response);
}else if("preupdate".equals(method)){
preUpdate(request,response);
}else if("update".equals(method)){
update(request,response,smart);
}
}
注意:
SmartUpload 初始化方式:smart.initialize(super.getServletConfig(), request, response);
如果在jsp中使用 则初始化方式为:
smart.initialize(pageContext);
表单要注意封装:用enctype封装
<form action="../servlet/smartUpateServlet" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>相片1:</td>
<td><input type="file" name="pic1"/></td>
</tr>
<tr>
<td>相片2:</td>
<td><input type="file" name="pic2"/></td>
</tr>
<tr>
<td>相片3:</td>
<td><input type="file" name="pic3"/></td>
</tr>
<tr>
<td><input type="submit" value="上传"/></td>
<td>
<input type="reset" value="重置"/>
<input type="hidden" name="method" value="upload"/>
</td>
</tr>
<tr>
<td colspan="2">
<font><%=(request.getAttribute("message")==null?" ":request.getAttribute("message")) %></font>
</td>
</tr>
</table>
</form>
由于表单进行了封装后台取得参数时,不能直接使用 request.getParameter(String param)而是在smart.upload()之后使用smart.getRequest().getParameter(String param)
上传代码:
IPTimeStamp its = new IPTimeStamp(request.getRemoteAddr());
for (int x = 0; x < smart.getFiles().getCount(); x++) {
String ext = smart.getFiles().getFile(x).getFileExt();
String fileName = its.getIPTimeRand() + "." + ext;
String sql = "insert into image(photo,userid) values(?,?)";
pre = conn.prepareStatement(sql);
pre.setString(1, fileName);
pre.setInt(2, user.getId());
int n = pre.executeUpdate();
if (n > 0) {
flag = true;
}
if (flag == true) {
smart.getFiles().getFile(x).saveAs(getServletContext().getRealPath("/") + "upload"+ File.separator + fileName);// 保存文件
}
}
以上代码测试正确 但仅供参考,由于时间关系 代码风格不好,看起来很不舒服,仅供理解原理