当前位置:首页 > 开发 > Web前端 > JavaScript > 正文

jsp上传文件

发表于: 2015-04-20   作者:香水浓   来源:转载   浏览:
摘要: 1. jsp上传 Notice: 1. form表单 method 属性必须设置为 POST 方法 ,不能使用 GET 方法 2. form表单 enctype 属性需要设置为 multipart/form-data 3. form表单 action 属性需要设置为提交到后台处理文件上传的jsp文件地址或者servlet地址。例如 uploadFile.jsp 程序文件用来处理上传的文
1. jsp上传
Notice:
1. form表单 method 属性必须设置为 POST 方法 ,不能使用 GET 方法
2. form表单 enctype 属性需要设置为 multipart/form-data
3. form表单 action 属性需要设置为提交到后台处理文件上传的jsp文件地址或者servlet地址。例如 uploadFile.jsp 程序文件用来处理上传的文件
4. 上传文件元素需要使用 <input .../> 标签,属性设置为 type="file"。如果需要上传多个文件,可以在 <input .../>标签中设置不同的名称

Steps
    首先我们先定义文件上传后存储在服务上的位置,你可以将路径写在你的程序当中,或者我们可以在web.xml配置文件中通过设置 context-param 元素来设置文件存储的目录
	<context-param>
		<param-name>file_upload_dir</param-name>
		<param-value>F:\files_uploaded</param-value>
		<description>Location to store uploaded files</description>
	</context-param>	

    依赖 FileUpload, 所以你需要在你的classpath中引入最新的 commons-fileupload.x.x.jar 包文件
    FileUpload 依赖 Commons IO, 所以你需要在你的classpath中引入最新的 commons-io-x.x.jar
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
			<version>1.3.2</version>
		</dependency>

    在测试以下实例时,你需要上传确认上传的文件大小小于 maxFileSize 变量设置的大小 ,否则文件无法上传成功
    确保你已经创建了目录F:\files_uploaded

fileupload.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>Up load file</title>
</head>
<body>
	<form action="processFileUpload.jsp" method="post" enctype="multipart/form-data">
		<input type="file" size="50" name="fileSelected">
		<input type="submit" value="upload">
	</form>
</body>
</html>


processFileUpload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>    
<%@ page import="java.io.*,java.util.*,javax.servlet.*" %>   
<%@ page import="org.apache.commons.fileupload.*" %> 
<!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>Insert title here</title>
</head>
<body>
<%
	File file;
	int maxSize = 1024*1024*1024;
	int maxMemSize = 1024*1024;
	ServletContext ctx = pageContext.getServletContext();
	String filePath = ctx.getInitParameter("file_upload_dir");
	String contentType = request.getContentType();
	if(ServletFileUpload.isMultipartContent(request)) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(maxMemSize); //设置内存中存储文件的最大值
		factory.setRepository(new File("F:\\tmp"));
		ServletFileUpload servlet = new ServletFileUpload(factory);
		servlet.setSizeMax(maxSize); //设置最大的上传文件大小
		
		try {
			List items = servlet.parseRequest(request);
			out.println(items.size());
			Iterator it = items.iterator();
			while(it.hasNext()) {
				FileItem item = (FileItem) it.next();
				String fieldName = item.getFieldName();
				String fileName = item.getName();
				boolean isInMemory = item.isInMemory();
				long sizeInBytes = item.getSize();
				
				if(fileName.lastIndexOf("\\") >= 0) {
					file = new File(filePath, fileName.substring(fileName.lastIndexOf("\\")));
				} else {
					file = new File(filePath, fileName.substring(fileName.lastIndexOf("\\")+1));
				}
				
				item.write(file);
				out.println("Uploaded file: " + fileName);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
%>
</body>
</html>


NOTE:
    代码copy自网络,起初,processFileUpload.jsp中的List items = servlet.parseRequest(request);得到的总是空集合,网上也有很多遇到这种情况的,原因 在fileupload.jsp: name="fileSelected" , 如果没有name标记,commons fielupload不会作处理
    servlet.setHeaderEncoding("UTF-8");中文名不会乱码

2. servlet上传
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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 FileUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 849325874174997377L;
	private static final int sizeThreshold = 1024*1024*1024;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println(".....doGet.....");
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletContext ctx = this.getServletContext();
		String filePath = ctx.getInitParameter("file_upload_dir");
		factory.setRepository(new File(filePath));
		factory.setSizeThreshold(sizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		try {
			@SuppressWarnings("unchecked")
			List<FileItem> list = upload.parseRequest(req);
			for(FileItem item : list) {
				String name = item.getFieldName();
				if(item.isFormField()) {
//					String value = item.getString();
//					req.setAttribute(name, value);
				} else {
					String value = item.getName();
					String fileName = value.substring(value.indexOf("\\")+1);
					req.setAttribute(name, fileName);
					OutputStream os = new FileOutputStream(new File(filePath, fileName));
					InputStream is = item.getInputStream();
					
					byte[] buff = new byte[1024];
					System.out.println("The length of " + value + " is " + item.getSize());
					
					int length = 0;
					while((length = is.read(buff)) != -1) {
						os.write(buff, 0, length);
					}
					is.close();
					os.close();
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		
		req.getRequestDispatcher("pages/upload_result.jsp").forward(req, resp);
	}

}


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class EncodingFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("init EncodingFilter....");
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");
		System.out.println("set the encoding to be utf-8 in EncodingFilter...");
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		System.out.println("destroy EncodingFilter....");
	}

}


fileupload.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>Up load file</title>
</head>
<body>
	<form action="<%=request.getContextPath() %>/fileupload" method="post" enctype="multipart/form-data">
		<input type="file" size="50" name="fileSelected">
		<input type="submit" value="upload">
	</form>
</body>
</html>


upload_result.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>Insert title here</title>
</head>
<body>
<h3>File <%=request.getAttribute("fileSelected") %> uploaded successfully.</h3>
</body>
</html>


web.xml
<web-app>
	<display-name>Archetype Created Web Application</display-name>
	
	<context-param>
		<param-name>file_upload_dir</param-name>
		<param-value>F:\files_uploaded</param-value>
		<description>Location to store uploaded files</description>
	</context-param>	

	 <filter>
	 	<filter-name>EncodingFilter</filter-name>
	 	<filter-class>com.jesse.jsp.filter.EncodingFilter</filter-class>
	 </filter>
	 
	 <filter-mapping>
	 	<filter-name>EncodingFilter</filter-name>
	 	<url-pattern>/*</url-pattern>
	 </filter-mapping>
	 
	 <servlet>
	 	<servlet-name>fileUploadServlet</servlet-name>
	 	<servlet-class>com.jesse.jsp.servlet.FileUploadServlet</servlet-class>
	 </servlet>
	 
	 <servlet-mapping>
	 	<servlet-name>fileUploadServlet</servlet-name>
	 	<url-pattern>/fileupload</url-pattern>
	 </servlet-mapping>
</web-app>

jsp上传文件

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
需要一个SmartUpload包 我找的一个下载地址http://dl2.csdn.net/down4/20070620/20110848916.jar 这
很早以前就想把CKEditor在JSP下的图片上传及浏览服务器图片的方法写下来了,不过因为教学项目中要用
上传文件例子如下 <%@ page contentType="text/html;charset=GB2312" %> <HTML> <he
最近学习使用ckfinder实现文件上传,下面详细介绍一下ckfinder在JSP中的应用 1、下载ckfinder ckfin
a.在jsp中简单利用Commons-fileupload组件实现 b.在struts1.2中实现 c.在sturts2中实现 注:此为三个
CKEditor 在jsp中实现文件上传的完整例子 2010-03-26 12:23:01| 分类: struts2|字号 订阅 <p st
请不要妄想,一个html的file控件,再加上javascript与jquery语句就可以完成文件上传, 文件上传系统
关键代码如下: index.jsp [html] view plain copy print ? <body> <span clas
原文地址: http://blog.csdn.net/a125138/article/details/8103732 关键代码如下: index.jsp <
关键代码如下: index.jsp <body> <center> <h3>文件上传</h3> <font c
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号