servlet3.0(JDK1.6)自带的API即可实现本地文件的上传,Servlet3.0新增了Part接口,HttpServletRequest的getPart()方法取得Part实现对象。下面我实现了文件的上传以及将上传的文件显示在网页上(主要目的是实现本地文件在网页上的显示,我采取了先上传文件,在读取上传的文件,将读取的内容显示在网页上)。
Java代码实现:
package FileUpload.servlet; import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part; /**
* Servlet implementation class FileUploadServlet
*/
//上传文件被保存的路径
@MultipartConfig(
location="E:\\eclipse\\workspace\\TestAceEditor\\FileUpload"
)
@WebServlet(urlPatterns={"/fileUpload"}) public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//private static final Log log = LogFactory.getLog(UploadFileAction.class);
//private String fileNameExtractorRegex = "filename=\".+\""; /**
* @see HttpServlet#HttpServlet()
*/
public FileUploadServlet() {
super();
// TODO Auto-generated constructor stub
} //获得指定文件的内容
private String getFileContent(String fileName){
File file = new File(fileName);
BufferedReader reader = null;
String ans = "";
try{
reader = new BufferedReader(new FileReader(file));
String tmpString = null;
//一行一行的读取文件里面的内容
while((tmpString = reader.readLine()) != null){
ans += tmpString + "\n";//保存在ans里面
}
}catch(IOException e){
e.printStackTrace();
}finally{
if(reader != null)
{
try{
reader.close();
}catch(IOException e1){
e1.printStackTrace();
}
}
}
//返回获得的文件内容
return ans;
}
//获得上传文件的文件名
private String getFilename(Part part){ if(part == null){
return null;
}
//获得文件名的方法是根据一本书上的代码来的,忘记书名了,以后补上
String contentDispositionHeader = part.getHeader("content-disposition"); String fileName = null;
String[] elements = contentDispositionHeader.split(";");
for(String element:elements){
if(element.trim().startsWith("filename")){
fileName = element.substring(element.indexOf('=') + 1).trim().replace("\"", "");
break;
}
}
fileName = fileName.substring(fileName.lastIndexOf('\\') + 1);
// Pattern pattern = Pattern.compile(fileNameExtractorRegex);
// Matcher matcher = pattern.matcher(contentDispositionHeader);
// String fileName = null;
// if(matcher.find()){
// fileName = matcher.group();
// fileName = fileName.substring(10, fileName.length()-1);
// } return fileName;
} /**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.getRequestDispatcher("fileUpload.jsp").forward(request, response);
} /**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//set the encoding
request.setCharacterEncoding("UTF-8"); //请求(form中为file类型的输入框的名字为filename)发送过来时,使用getPart()方法取得Part实现对象
Part part = request.getPart("filename");
String fileName = getFilename(part); if(fileName != null && !fileName.isEmpty()){
part.write(fileName);
} //从指定文件路径获得文件内容
String filePath = "E:\\eclipse\\workspace\\TestAceEditor\\FileUpload" + "\\" + fileName;
String fileContent = getFileContent(filePath); //write to browser
// response.setContentType("text/html");
// PrintWriter writer = response.getWriter();
// writer.print("<br/>Uploaded file name: "+ fileName);
// writer.print("<br/>Size: "+part.getSize());
//
// String author = request.getParameter("author");
// writer.print("<br/>Author: "+author);
//设置属性,在jsp文件中可以使用EL获得fileContent对象里的内容
request.setAttribute("fileContent", fileContent);
request.getRequestDispatcher("fileUpload.jsp").forward(request, response); } }
jsp代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>fileupload</title> <style type="text/css" media="screen">
body {
overflow: hidden;
} #editor {
margin: 0;
position: absolute;
top: 130px;
bottom: 0;
left: 0;
right: 0;
}
</style> </head> <body> <div style="margin:left">
<h1>editor my code</h1>
</div> <div style="background:#BFEFFF">
<form action="fileUpload" enctype="multipart/form-data" method="post">
Select file to show <input type="file" name="filename"/>
<input type="submit" value="Show"/>
</form>
</div> <div id="editor">
<!-- show the content in the uploading file -->
${fileContent}
</div> </body>
</html>
上传效果如下:
不用管里面说的图2(其实就是Java代码中说的MultipartConfig中的location),我把之前写文档的截图直接拿过来~
注意编码,统一utf-8吧,包括上传的文件的编码。