servlet的上传文件

来源:互联网 发布:苹果远程软件 编辑:程序博客网 时间:2024/06/15 01:53

1.servlet部分

public class usephotoServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Usephoto up = new Usephoto();
try {
//文件的上传
//创建上传文件的对象
SmartUpload smart = new SmartUpload();
//初始化该对象
smart.initialize(this.getServletConfig(), request, response);
//设置允许上传的文件的后缀
smart.setAllowedFilesList("jpg");
//设置不能上传的文件的类型
smart.setDeniedFilesList("exe");
//设置单个文件允许上传的大小
smart.setMaxFileSize(1024*1024*10);
//设置总共允许上传的总共大小
smart.setTotalMaxFileSize(1024*1024*15);

//准备上传
smart.upload();

//通过smartupload对象获取request对象
Request r = smart.getRequest();
String upName = null;
String uid = r.getParameter("uid");
//获取表单中所有的file类型 的控件,返回一个Files
Files filelist= smart.getFiles();

//获取项目的路径
String path= this.getServletContext().getRealPath("\\")+"Upload\\";
//遍历控件
//filelist.getCount():获取当前控件的个数
for(int i=0;i<filelist.getCount();i++){
//filelist.getFile(i):获取当前的控件
File file = filelist.getFile(i);
//判断当前控件是否被选中
//isMissing():是否被选中,选中返回false,没有选中返回true
if(!file.isMissing()){
//获取该文件的文件名称
String name=file.getFileName();
//获取随机名
name =GetFileName.getFileName(name);
upName=name;
//保存文件
file.saveAs(path+name);
}
}
up.setUid(uid);
up.setUpName(upName);
} catch (SQLException e) {
e.printStackTrace();
} catch (SmartUploadException e) {
e.printStackTrace();
}
usephotoDaoImp udaoimp = new usephotoDaoImp();
udaoimp.addUsePhoto(up);
List<Usephoto> uplist  =udaoimp.seleUsePhoto(up.getUid(),6, 1);
HttpSession session = request.getSession();
session.setAttribute("uplist", uplist);
response.sendRedirect("oneTimeBoby/myPhoto.jsp");
}

}

2.jsp部分

<form action="usephotoServlet" method="post"  enctype="multipart/form-data" >
<table>
<tr><td colspan="2"><input type="hidden" name="uid" value="${sessionScope.u.uid }"/></td></tr>
<tr>
<td><input type="file" name="uImg"/><input type="text" name="tphoto"/></td><td><input type="submit" value="确认上传"/></td></tr>
</table>
</form>

3.jar包

jspsmartupload.jar

0 0
原创粉丝点击