Servlet3.0 上传文件实例

1、相关函数的说明

(1)request.getSchem()->获取协议头,如http

(2)request.getHostName->获取主机名

(3)request.getPort()->获取端口号

(4)request.getContextPath()->获取请求的资源路径,形如http://localhost::8080下面的ServletDemo

(5)part.getHeader(“content-disposition”)->获取传输的头部信息

(6)getServletContext().getRealPath->获取绝对路径

2、注意问题

上传文件夹必须存在,如果不存在则会报FileNotFoundException(花了好长时间)

3、编程---新建web工程-新建如下文件

上传界面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Upload File Index</title>
</head>
<body>
<form action="UpFile" method="post" enctype="multipart/form-data">
<table>
	<tr>
		<td>Select File:</td><td><input type="file" name="file"></td>
	</tr>
	<tr>
		<td>Description:</td><td><input type="text" name="description"></td>
	</tr>
	<tr>
		<td colspan="2"><input type="submit" value="Submit">   <input type="reset" value="Reset"></td>
	</tr>
</table>
</form>
</body>
</html>

处理servlet

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

/**
 * Servlet implementation class FileUploadServlet
 */
@WebServlet(name="upFile",urlPatterns={"/UpFile"})
@MultipartConfig(maxFileSize=500000,maxRequestSize=-1)
public class FileUploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public FileUploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		Part part=request.getPart("file");
		String header=part.getHeader("content-disposition");
		String storePath=this.getServletContext().getRealPath("/temp");
		String suffix=ParseFileName(header);
		String name=UUID.randomUUID()+suffix;
		File f=new File(storePath + File.separator+name);
		if(!f.exists()){
			f.createNewFile();
		}
		part.write(storePath + File.separator+name);
		
		String description= request.getParameter("description"); 
		request.setAttribute("f", name);
		request.setAttribute("des", description);
		request.getRequestDispatcher("info.jsp").forward(request, response);
		
	}
	
	private String ParseFileName(String info){
		String str;
		str=info.substring(info.lastIndexOf("."),info.length()-1);
		return str;
	}

}

显示界面

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<% 
	String filename=(String)request.getAttribute("f");
	String path=request.getContextPath();
	String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
  
<!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=ISO-8859-1">
<title>Info Page</title>
</head>
<body>
<h3><%=request.getAttribute("des") %></h3>
<img src="<%=basePath %>temp/<%=filename%>">
</body>
</html>



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。