Home  >  Article  >  Web Front-end  >  Servlet+Jsp implements the specific ideas and code for uploading pictures or files

Servlet+Jsp implements the specific ideas and code for uploading pictures or files

高洛峰
高洛峰Original
2016-12-24 17:27:03926browse

现在不管是博客论坛还是企业办公,都离不开资源的共享。通过文件上传的方式,与大家同分享,从而达到大众间广泛的沟通和交流,我们既可以从中获得更多的知识和经验,也能通过他人的反馈达到自我改进和提升的目的。

下面我就为大家介绍 web项目中的这一上传功能,那么文件是如何从本地发送到服务器的呢?看我慢慢道来: 
首先,我们创建一个新的web工程,在工程的WebRoot目录下新建一个upload文件夹,这样当我们将该工程部署到服务器上时,服务器便也生成个upload文件夹,用来存放上传的资源。

然后,在WebRoot目录下新建一个jsp文件,主要实现的作用就是选择上传的文件,提交至servlet来进行处理 
详细代码如下:一个form将文件信息通过post方式传送到指定的servlet 

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<base href="<%=basePath%>"> 
<title>My JSP &#39;upload.jsp&#39; starting page</title> 
<meta http-equiv="pragma" content="no-cache"> 
<meta http-equiv="cache-control" content="no-cache"> 
<meta http-equiv="expires" content="0"> 
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
<meta http-equiv="description" content="This is my page"> 
<!-- 
<link rel="stylesheet" type="text/css" href="styles.css"> 
--> 
</head> 
<body> 
<form action="/upload/UpLoad" method="post" enctype="multipart/form-data"> 
请选择上传的图片或文件:<input type="file" name="fileName"/><input type="submit" value="上传"/> 
</form> 
</body> 
</html>

可以看到,我们将数据提交到工程下的upload/UpLoad。 
之后,我们就来编写这个servlet——UpLoad.java 

package load; 
import java.io.File; 
import java.io.IOException; 
import java.io.PrintWriter; 
import java.util.List; 
import javax.servlet.ServletContext; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
public class UpLoad extends HttpServlet { 
@SuppressWarnings("unchecked") 
@Override 
protected void service(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException { 
req.setCharacterEncoding("utf-8"); 
resp.setContentType("text/html;charset=utf-8"); 
//为解析类提供配置信息 
DiskFileItemFactory factory = new DiskFileItemFactory(); 
//创建解析类的实例 
ServletFileUpload sfu = new ServletFileUpload(factory); 
//开始解析 
sfu.setFileSizeMax(1024*400); 
//每个表单域中数据会封装到一个对应的FileItem对象上 
try { 
List<FileItem> items = sfu.parseRequest(req); 
//区分表单域 
for (int i = 0; i < items.size(); i++) { 
FileItem item = items.get(i); 
//isFormField为true,表示这不是文件上传表单域 
if(!item.isFormField()){ 
ServletContext sctx = getServletContext(); 
//获得存放文件的物理路径 
//upload下的某个文件夹 得到当前在线的用户 找到对应的文件夹 

String path = sctx.getRealPath("/upload"); 
System.out.println(path); 
//获得文件名 
String fileName = item.getName(); 
System.out.println(fileName); 
//该方法在某些平台(操作系统),会返回路径+文件名 
fileName = fileName.substring(fileName.lastIndexOf("/")+1); 
File file = new File(path+"\\"+fileName); 
if(!file.exists()){ 
item.write(file); 
//将上传图片的名字记录到数据库中 

resp.sendRedirect("/upload/ok.html"); 
} 
} 
} 
} catch (Exception e) { 
e.printStackTrace(); 
} 

} 
}

因为已对 代码做了详细的注释,所以相信大家也能基本上传的这个过程。要注意的一点是解析实例空间大小的设置。我们希望上传的文件不会是无限大,因此,设置 

.setFileSizeMax(1024*400);

在这儿我们也可以将其设置成一个条件,当文件大于最大值时向页面 提交错误提示。此外,也可以读取选择文件的后缀来筛选出可以上传的类型。这些代码大家自己扩展,不再细谈。

通过servlet, 将正确的文件传送到服务端的upload文件夹中。这儿要注意,如果以后将工程从tomcat移除后,这些文件就会被自动删除。

上传结束之后,使页面转到上传成功页面ok.html。 当用户看到此页面时,说明你已实现文件的上传功能。


更多Servlet+Jsp实现图片或文件的上传功能具体思路及代码相关文章请关注PHP中文网!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn