URL:http://www.cnblogs.com/ISeeYouBlogs/p/jsp.html
1.要实现图片上传,首先需要一个组件,这里我用的是smartupload.jar可以到这里下载http://download.csdn.net/detail/mengdecike/8279247
2.下载之后把这个文件直接复制到WebContent/WEB-INF/lib下面
3.jsp页面
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <title>Insert title here</title>
8 </head>
9 <body>
10 <form action="UpLoad" method="post" enctype="multipart/form-data" name="form1">
11 <p>用户名:
12 <label for="username"></label>
13 <input type="text" name="username" id="username">
14 </p>
15 <p>头 像:
16 <label for="photo"></label>
17 <input type="file" name="photo" id="photo">
18 </p>
19 <p>
20 <input type="submit" name="button" id="button" value=" 提 交 ">
21 </p>
22 </form>
23 </body>
24 </html>
4.上传的servlet代码如下:
1
request.setCharacterEncoding("utf-8");//设置字符
2 response.setContentType("text/html;charset=utf-8");
3 response.setCharacterEncoding("utf-8");
4 PrintWriter out =response.getWriter();//获取out输出对象
5
6 // 准备上传目录
7 String path = this.getServletContext().getRealPath("images");
8 File fpath = new File(path);
9 if(!fpath.exists()){
10 fpath.mkdir();
11 }
12
13 // 实例化组件
14 SmartUpload su = new SmartUpload("utf-8");
15 // 初始化组件
16 su.initialize(this.getServletConfig(), request, response);
17
18 try {
19 // 限定
20 su.setAllowedFilesList("jpg,png,gif");
21 su.setMaxFileSize(50*1024); // 不能超过50K
22
23 // 上传并提取文件
24 su.upload();
25 SmartFile file = su.getFiles().getFile(0);
26 // 生成文件名
27 String fname = new Date().getTime()+"."+file.getFileExt();
28 // 保存文件
29 file.saveAs(path+"/"+fname);
30 //file.saveAs(path+"/"+fname,1);
31 // 提示
32 out.println("<script>alert('文件上传成功!');location.href='upload.jsp';</script>");
33
34 // 提取字段信息
35 String username = su.getRequest().getParameter("username");
36 System.out.println(">>> " + username);
37
38 // 进行数据库操作
39
40
41 } catch(SecurityException e){
42 out.println("<script>alert('只能上传jpg、png、gif的文件并且不能超过50K!');history.back();</script>");
43 e.printStackTrace();
44 }
45 catch (SmartUploadException e) {
46 // TODO Auto-generated catch block
47 out.println("<script>alert('文件上传失败!');history.back();</script>");
48 e.printStackTrace();
49 }
50