JSP实现文件上传,解决上传文件名为乱码问题

    最近写项目用到JSP上传文件,网上的资料较少,且出现的问题也多,中文乱码问题的解决方案也不是很全很完整,基于此,

在查阅大量文件后,依赖FileUpload 和Commons IO 的文件上传比较好,它依赖于两个jar包库:

commons-fileupload.x.x.jar 包,下载地址:http://commons.apache.org/fileupload/commons-io-x.x.jar包,下载地

址:http://commons.apache.org/io/ 。将两个包下载下来后,可以配置环境的classpath引入俩个包,或者也可以直接将包拷贝到

tomcat的lib目录下,刷新eclipse即可。解决中文文件名的乱码问题主要是注意编码要用GBK编码,下面是源码:


upload.jsp

<%@ page language="java" contentType="text/html; charset=gbk"
    pageEncoding="gbk"%>




文件上传


请选择上传的文件:




doupload.jsp

<%@ page language="java" contentType="text/html; charset=gbk"
    pageEncoding="gbk"%>
<%@ page import="java.io.*,java.util.*, javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.io.output.*"%>

<%
	File file;
	int maxFileSize = 5000 * 1024;
	int maxMemSize = 5000 * 1024;
	ServletContext context = pageContext.getServletContext();
	String filePath = "E://Tomcat/apache/webapps/data/";  //文件存储路径

	// 验证上传内容了类型
	String contentType = request.getContentType();
	if ((contentType.indexOf("multipart/form-data") >= 0)) {

		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存中存储文件的最大值
		factory.setSizeThreshold(maxMemSize);
		// 本地存储的数据大于 maxMemSize.
		factory.setRepository(new File("F:\\temp"));

		// 创建一个新的文件上传处理程序
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置最大上传的文件大小
		upload.setSizeMax(maxFileSize);
		try {
			// 解析获取的文件
			List fileItems = upload.parseRequest(request);

			// 处理上传的文件
			Iterator i = fileItems.iterator();

			out.println("");
			out.println("");
			out.println("JSP File upload");
			out.println("");
			out.println("");
			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				if (!fi.isFormField()) {
					// 获取上传文件的参数
					String fieldName = fi.getFieldName();
					String fileName = fi.getName();
					boolean isInMemory = fi.isInMemory();
					long sizeInBytes = fi.getSize();
					// 写入文件
					if (fileName.lastIndexOf("\\") >= 0) {
						file = new File(filePath,
								fileName.substring(fileName
										.lastIndexOf("\\")));
					} else {
						file = new File(filePath,
								fileName.substring(fileName
										.lastIndexOf("\\") + 1));
					}
					fi.write(file);
					out.println("Uploaded Filename: " + filePath
							+ fileName + "
"); } } out.println(""); out.println(""); } catch (Exception ex) { System.out.println(ex); } } else { out.println(""); out.println(""); out.println("Servlet upload"); out.println(""); out.println(""); out.println("

No file uploaded

"); out.println(""); out.println(""); } %>

本人经验,仅供参考!

你可能感兴趣的:(JSP)