码迷,mamicode.com
首页 > Web开发 > 详细

一个用于上传文件的servlet

时间:2015-09-04 22:28:37      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

1、jsp页面操作文件:

 1 <%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
 2 <html>
 3   <head>
 4     <title>上传文件 </title>
 5     <link rel="stylesheet" type="text/css" href="../css/uploadfile.css">
 6     <link rel="stylesheet" type="text/css" href="../css/footer.css">
 7     <script type="text/javascript" src="../js/uploadfile.js"></script>
 8   </head>
 9   <body>
10   <div class="container">
11   <form action="../upLoadFileServlet" name="uploadform" enctype="multipart/form-data" method="post">
12       <div class="back"><span class="cleckback" onclick="javascript:history.back()" style="padding-right: 50px;">返回上一级</span></div>
13       <div class="upfile-div" align="center">
14           <div class="title-div">上传文件</div>
15         <table class="toggle-table">
16            <tr>
17                <td>上传者姓名:</td>
18                <td><input type="text" id="uploadfileuser" name="uploadfileusername" class="inputname"/></td>
19            </tr>
20            <tr>
21                <td>&nbsp;&nbsp;&nbsp;间:</td>
22                <td><input type="datetime-local" class="inputtime"></td>
23            </tr>
24            <tr>
25                <td>选择上传文件:</td>
26                <td><input type="file" name="uploadfile" class="seclectedfile"/></td>
27            </tr>
28            </table>
29            <div class="toggle-btns">
30                <input type="submit" value="上传" class="mybtn"/>
31                <input type="button" value="取消" class="mybtn" onclick="uploadUserCheck()"/>
32            </div>
33     </div>
34     </form>
35   </div>
36   <div class="footer"><jsp:include page="footer.jsp"></jsp:include></div>  
37   </body>
38 </html>

2、uploadresult.jsp:

 1 <%@ page language="java" import="java.util.*" contentType="text/html; charset=gb2312"%>
 2 <%
 3 String path = request.getContextPath();
 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 5 %>
 6 
 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 8 <html>
 9   <head>
10     <base href="<%=basePath%>">
11     
12     <title>My JSP ‘uploadresult.jsp‘ starting page</title>
13     
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22 
23   </head>
24   
25   <body>
26   <p>121312313132123132</p>
27     <%
28         String msg = (String)request.getAttribute("upload.message");
29         if (msg != null)
30         {
31             %>
32                 <%= msg %>
33             <%
34         }
35      %>
36   </body>
37 </html>

 

3、servlet:

 1 package web.servlet;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.util.Iterator;
 6 import java.util.List;
 7 
 8 import javax.servlet.ServletException;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 
13 import org.apache.commons.fileupload.FileItem;
14 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
15 import org.apache.commons.fileupload.servlet.ServletFileUpload;
16 
17 @SuppressWarnings("serial")
18 public class UpLoadFileServlet extends HttpServlet {
19     
20     private int cachesize = 1024 * 1024;
21     
22     public void doGet(HttpServletRequest request, HttpServletResponse response)
23             throws ServletException, IOException {
24 
25         this.doPost(request, response);
26     }
27 
28     public void doPost(HttpServletRequest request, HttpServletResponse response)
29             throws ServletException, IOException {
30 
31         response.setCharacterEncoding("gb2312");
32         response.setContentType("text/html;charset=gb2312");
33         request.setCharacterEncoding("gb2312");
34         String uploadfileUserName = request.getParameter("uploadfileusername");
35         
36 //        System.out.println(uploadfileUserName);
37         
38         DiskFileItemFactory factory = new DiskFileItemFactory();
39         factory.setRepository(new File("e:/tmp/"));//设置文件缓存路径
40         factory.setSizeThreshold(cachesize);  //设置文件上传的上限,-1表示无上限
41         ServletFileUpload upload = new ServletFileUpload(factory);
42         if (!ServletFileUpload.isMultipartContent(request)){
43             return;
44         }
45         try {
46             
47             @SuppressWarnings("unchecked")
48             List<FileItem> items = upload.parseRequest(request);//上传文件并解析出所有字段
49             Iterator<FileItem> iter = items.iterator();
50             while(iter.hasNext())
51             {
52                 FileItem item = iter.next();
53                 if (item.isFormField())  //表单字段
54                 {
55                     System.out.println(item.getFieldName());
56                     System.out.println(item.getString());
57                 }
58                 else
59                 {
60                     if (item.getName() != null && !item.equals(""))
61                     {
62                         System.out.println(item.getName());
63                         
64                         File tempFile = new File(item.getName());  //获得临时文件(创建内存文件)
65                         String filename = tempFile.getName();
66                         
67                         File file = new File(this.getServletContext().getRealPath("/")+"AcceptedUploadFiles",filename);
68 //                        OutputStream os = new FileOutputStream(file);
69                         item.write(file);
70                         request.setAttribute("upload.message", "成功上传文件:"+filename);
71                     }
72                     else
73                     {
74                         request.setAttribute("upload.message", "请选择上传文件");
75                     }
76                     
77                 }
78             }
79         } catch (Exception e) {
80             request.setAttribute("upload.message", "文件上传失败");
81         }
82         //dispatcher跳转其他资源
83         request.getRequestDispatcher("jsp/uploadresult.jsp").forward(request,response);
84     }
85 
86 }

 

一个用于上传文件的servlet

标签:

原文地址:http://www.cnblogs.com/0519xf/p/4782424.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!