Shirlies
宁静专注认真的程序媛~

servlet3.0(JDK1.6)自带的API即可实现本地文件的上传,Servlet3.0新增了Part接口,HttpServletRequest的getPart()方法取得Part实现对象。下面我实现了文件的上传以及将上传的文件显示在网页上(主要目的是实现本地文件在网页上的显示,我采取了先上传文件,在读取上传的文件,将读取的内容显示在网页上)。

Java代码实现:

  1 package FileUpload.servlet;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileReader;
  6 import java.io.IOException;
  7 import java.io.PrintWriter;
  8 
  9 import javax.servlet.ServletException;
 10 import javax.servlet.annotation.*;
 11 import javax.servlet.http.HttpServlet;
 12 import javax.servlet.http.HttpServletRequest;
 13 import javax.servlet.http.HttpServletResponse;
 14 import javax.servlet.http.Part;
 15 
 16 /**
 17  * Servlet implementation class FileUploadServlet
 18  */
 19 //上传文件被保存的路径
 20 @MultipartConfig(
 21         location="E:\\eclipse\\workspace\\TestAceEditor\\FileUpload"
 22         )
 23 @WebServlet(urlPatterns={"/fileUpload"})
 24 
 25 public class FileUploadServlet extends HttpServlet {
 26     private static final long serialVersionUID = 1L;
 27     //private static final Log log = LogFactory.getLog(UploadFileAction.class);
 28     //private String fileNameExtractorRegex = "filename=\".+\"";
 29     
 30     /**
 31      * @see HttpServlet#HttpServlet()
 32      */
 33     public FileUploadServlet() {
 34         super();
 35         // TODO Auto-generated constructor stub
 36     }
 37 
 38     //获得指定文件的内容
 39     private String getFileContent(String fileName){
 40         File file = new File(fileName);
 41         BufferedReader reader = null;
 42         String ans = "";
 43         try{
 44             reader = new BufferedReader(new FileReader(file));
 45             String tmpString = null;
 46             //一行一行的读取文件里面的内容
 47             while((tmpString = reader.readLine()) != null){
 48                 ans += tmpString + "\n";//保存在ans里面
 49             }
 50         }catch(IOException e){
 51             e.printStackTrace();
 52         }finally{
 53             if(reader != null)
 54             {
 55                 try{
 56                     reader.close();
 57                 }catch(IOException e1){
 58                     e1.printStackTrace();
 59                 }
 60             }
 61         }
 62         //返回获得的文件内容
 63         return ans;
 64     }
 65     //获得上传文件的文件名
 66     private String getFilename(Part part){
 67         
 68         if(part == null){
 69             return null;
 70         }
 71         //获得文件名的方法是根据一本书上的代码来的,忘记书名了,以后补上
 72         String contentDispositionHeader = part.getHeader("content-disposition");
 73         
 74         String fileName = null;
 75         String[] elements = contentDispositionHeader.split(";");
 76         for(String element:elements){
 77             if(element.trim().startsWith("filename")){
 78                 fileName = element.substring(element.indexOf('=') + 1).trim().replace("\"", "");
 79                 break;
 80             }
 81         }
 82         fileName = fileName.substring(fileName.lastIndexOf('\\') + 1);
 83 //        Pattern pattern = Pattern.compile(fileNameExtractorRegex);  
 84 //        Matcher matcher = pattern.matcher(contentDispositionHeader); 
 85 //        String fileName = null;
 86 //        if(matcher.find()){  
 87 //            fileName = matcher.group();  
 88 //            fileName = fileName.substring(10, fileName.length()-1);  
 89 //        }  
 90         
 91         return fileName;
 92     }
 93     
 94     /**
 95      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 96      */
 97     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 98         // TODO Auto-generated method stub
 99         request.getRequestDispatcher("fileUpload.jsp").forward(request, response);
100     }
101 
102     /**
103      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
104      */
105     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
106         // TODO Auto-generated method stub
107         //set the encoding
108         request.setCharacterEncoding("UTF-8");
109         
110         //请求(form中为file类型的输入框的名字为filename)发送过来时,使用getPart()方法取得Part实现对象
111         Part part = request.getPart("filename");
112         String fileName = getFilename(part);
113         
114         
115         if(fileName != null && !fileName.isEmpty()){
116             part.write(fileName);
117         }
118         
119         //从指定文件路径获得文件内容
120         String filePath = "E:\\eclipse\\workspace\\TestAceEditor\\FileUpload" + "\\" + fileName;
121         String fileContent = getFileContent(filePath);
122         
123         //write to browser
124 //        response.setContentType("text/html");
125 //        PrintWriter writer = response.getWriter();
126 //        writer.print("<br/>Uploaded file name: "+ fileName);
127 //        writer.print("<br/>Size: "+part.getSize());
128 //        
129 //        String author = request.getParameter("author");
130 //        writer.print("<br/>Author: "+author);
131         //设置属性,在jsp文件中可以使用EL获得fileContent对象里的内容
132         request.setAttribute("fileContent", fileContent);
133         request.getRequestDispatcher("fileUpload.jsp").forward(request, response);
134         
135     }
136 
137 }
View Code

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>fileupload</title>
 8 
 9 <style type="text/css" media="screen">
10     body {
11         overflow: hidden;
12     }
13     
14     #editor { 
15         margin: 0;
16         position: absolute;
17         top: 130px;
18         bottom: 0;
19         left: 0;
20         right: 0;
21     }
22  </style>
23  
24 </head>
25 
26 <body>
27 
28 <div style="margin:left">
29 <h1>editor my code</h1>
30 </div>
31 
32 <div style="background:#BFEFFF">
33 <form action="fileUpload" enctype="multipart/form-data" method="post">
34 Select file to show <input type="file" name="filename"/>
35 <input type="submit" value="Show"/>
36 </form>
37 </div>
38 
39 <div id="editor">
40 <!-- show the content in the uploading file -->
41 ${fileContent}
42 </div>
43 
44 </body>
45 </html>
View Code

上传效果如下:

不用管里面说的图2(其实就是Java代码中说的MultipartConfig中的location),我把之前写文档的截图直接拿过来~

注意编码,统一utf-8吧,包括上传的文件的编码。

 

posted on 2014-12-01 16:09  Shirlies  阅读(9051)  评论(0编辑  收藏  举报