使用fileupload上传文件总是出现失败!!!求解答

dxh308315 2013-05-26 02:21:32
使用的是commons-fileupload-1.3和commons-io-2.4

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.*;
import java.util.*;
import java.util.regex.*;
import java.io.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

public class FileUpload extends HttpServlet {
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html; charset=GB2312");
PrintWriter out = res.getWriter();
System.out.println(req.getContentLength());
System.out.println(req.getContentType());
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(4096);
// the location for saving data that is larger than getSizeThreshold()
factory.setRepository(new File("e:\\temp"));
System.out.println("e:\\temp");
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum size before a FileUploadException will be thrown
upload.setSizeMax(1000000);
try {
List fileItems = upload.parseRequest(req);
// assume we know there are two files. The first file is a small
// text file, the second is unknown and is written to a file on
// the server
Iterator iter = fileItems.iterator();

// 正则匹配,过滤路径取文件名
String regExp = ".+\\\\(.+)$";

// 过滤掉的文件类型
String[] errorType = { ".exe", ".com", ".cgi", ".asp" };
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// 忽略其他不是文件域的所有表单信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if ((name == null || name.equals("")) && size == 0)
continue;
Matcher m = p.matcher(name);
boolean result = m.find();
if (result) {
for (int temp = 0; temp < errorType.length; temp++) {
if (m.group(1).endsWith(errorType[temp])) {
throw new IOException(name + ": wrong type");
}
}
try {

// 保存上传的文件到指定的目录

// 在下文中上传文件至数据库时,将对这里改写
item.write(new File("d:\\" + m.group(1)));
System.out.println("d" );
out.print(name + "  " + size + "<br>");
} catch (Exception e) {
e.printStackTrace();
out.println(e);
}
} else {
throw new IOException("fail to upload");
}
}
}
} catch (IOException e) {
e.printStackTrace();
out.println(e);
} catch (FileUploadException e) {
e.printStackTrace();
out.println(e);
}

// 保存上传的文件到指定的目录

// 在下文中上传文件至数据库时,将对这里改写

}
public void init() throws ServletException {
// Put your code here
}
}
错误提示:
java.io.IOException: fail to upload
at com.dxh.shopping.servlet.FileUpload.doPost(FileUpload.java:80)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:619)
...全文
1508 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhangxm2015 2013-05-28
  • 打赏
  • 举报
回复
引用 6 楼 dxh308315 的回复:
非常非常感谢您!通过您的修改我的文件现在已经可以上传了!我会听取您的意见今后贴代码时会整理好格式,但是我仍然不知道使用正则表达式为什么不对,我的源代码在同学的电脑上是可以上传文件的,但是在我的电脑上却不可以(经过像你一样的修改后才可以上传)。
这个。。。。。。你的代码我也试了,真心不行。难道我上面解释错了。。。。这个我回头再看下。希望楼下大神给个详解!!!
dxh308315 2013-05-28
  • 打赏
  • 举报
回复
非常非常感谢您!通过您的修改我的文件现在已经可以上传了!我会听取您的意见今后贴代码时会整理好格式,但是我仍然不知道使用正则表达式为什么不对,我的源代码在同学的电脑上是可以上传文件的,但是在我的电脑上却不可以(经过像你一样的修改后才可以上传)。
zhangxm2015 2013-05-26
  • 打赏
  • 举报
回复
对于你的代码中的利用正则表达式进行过滤路径名,完全可以利用字符串的截取 间第62行
String filename = name.substring(name.lastIndexOf("\\") + 1);
对于你用
boolean result = m.find();
if (result) {
在匹配过程时,是一个文件一个文件进行的,这样你进行匹配时只能是一个文件所匹配的结果(而他只有一个),这样result就会是false。从而成生了上述现象。 建议楼主以后贴代码时,整理一下!!!
zhangxm2015 2013-05-26
  • 打赏
  • 举报
回复

package org.zhangming.load;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.*;
import java.util.*;
import java.io.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

public class FileUpLoad2 extends HttpServlet {
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	// Put your code here
	}
	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException 
	{
		res.setContentType("text/html; charset=GB2312");
		PrintWriter out = res.getWriter();
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		
		factory.setSizeThreshold(4096*1024);	// maximum size that will be stored in memory
		
		factory.setRepository(new File("e:/temp"));		// the location for saving data that is larger than getSizeThreshold()
		
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		upload.setSizeMax(1000000);		// maximum size before a FileUploadException will be thrown
		
		try {
				List fileItems = upload.parseRequest(req);
				/* 
				 * assume we know there are two files. The first file is a small
				* text file, the second is unknown and is written to a file on
				* the server
				*/
				Iterator iter = fileItems.iterator();

				// 正则匹配,过滤路径取文件名
//				String regExp = ".+\\\\(.+)$";

				// 过滤掉的文件类型
				String[] errorType = { ".exe", ".com", ".cgi", ".asp" };
//				Pattern p = Pattern.compile(regExp);
				while (iter.hasNext())
				{
					FileItem item = (FileItem) iter.next();
					
					// 忽略其他不是文件域的所有表单信息
					if (!item.isFormField()) 
					{
						String name = item.getName();
						String filename = name.substring(name.lastIndexOf("\\") + 1);
						long size = item.getSize();
						if ((name == null || name.equals("")) && size == 0)
							continue;
						System.out.println("-----------");
//						Matcher m = p.matcher(name);
//						boolean result = m.find();
						
							for (int temp = 0; temp < errorType.length; temp++) 
							{
								if (filename.endsWith(errorType[temp])) 
								{
									throw new IOException(name + ": wrong type");
								}
								else
								{
									// 保存上传的文件到指定的目录, 在下文中上传文件至数据库时,将对这里改写
									item.write(new File("d:\\",filename));

								}
							}
					}
				}
		
		} 
		catch (Exception e)
		{
			e.printStackTrace();
			out.println(e);
		}
	}
	public void init() throws ServletException {
		// Put your code here
	}
}
卿言戏语 2013-05-26
  • 打赏
  • 举报
回复
格式确实该规范一下了
无聊找乐 2013-05-26
  • 打赏
  • 举报
回复
代码格式乱的看不下去

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧