apache fileupload:
common-fileupload是jakarta项目组开发的一个功能很强大的上传文件组件
下面先介绍上传文件到服务器(多文件上传):
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.util.regex.*;
import org.apache.commons.fileupload.*;

public class upload extends HttpServlet ...{
private static final String CONTENT_TYPE = "text/html; charset=GB2312";
// Process the HTTP Post request
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException ...{
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
try ...{
DiskFileUpload fu = new DiskFileUpload();
// 设置允许用户上传文件大小,单位:字节,这里设为2m
fu.setSizeMax(2 * 1024 * 1024);
// 设置最多只允许在内存中存储的数据,单位:字节
fu.setSizeThreshold(4096);
// 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录
fu.setRepositoryPath("c:/windows/temp");
// 开始读取上传信息
List fileItems = fu.parseRequest(request);
// 依次处理每个上传的文件
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)));
out.print(name + " " + size + "<br>");
} catch (Exception e) ...{
out.println(e);
}

} else ...{
throw new IOException("fail to upload");
}
}
}
} catch (IOException e) ...{
out.println(e);
} catch (FileUploadException e) ...{
out.println(e);
}
}
}现在介绍上传文件到服务器,下面只写出相关代码:
以sql2000为例,表结构如下:
字段名:name filecode
类型: varchar image
数据库插入代码为:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");
代码如下:
。。。。。。
try{
//item.write(new File("d://" + m.group(1)));//这段代码如果不去掉,将一同写入到服务器中
int byteread=0;
InputStream inStream=item.getInputStream(); //读取输入流,也就是上传的文件内容
pstmt.setString(1,m.group(1));
pstmt.setBinaryStream(2,inStream,(int)size);
pstmt.executeUpdate();
inStream.close();
out.println(name+" "+size+"<br>");
}
。。。。。。
这样就实现了上传文件至数据库
文件上传原理:
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.PageContext;
//确定您的环境中存在如上包
public class upload ...{
private ServletRequest request;
private ServletResponse response;
private ServletConfig config;
ServletInputStream DATA;
int FormSize;
File f1;
FileOutputStream os;
DataInputStream is;
String filename;
byte[] b;
byte t;
boolean flag = false;

public upload() ...{
}
// 初始化
public void initialize(ServletConfig config, HttpServletRequest request,
HttpServletResponse response) throws IOException ...{
this.request = request;
this.response = response;
this.config = config;
DATA = request.getInputStream();
FormSize = request.getContentLength();
}

public void initialize(PageContext pageContext) throws IOException ...{
request = pageContext.getRequest();
response = pageContext.getResponse();
config = pageContext.getServletConfig();
DATA = request.getInputStream();
FormSize = request.getContentLength();
}

public boolean setFilename(String s) ...{
try ...{
File f1 = new File(s);
os = new FileOutputStream(f1);
} catch (IOException e) ...{
return (false);
}
return (true);
}

public void getByte() ...{
int i = 0;
try ...{
is = new DataInputStream(DATA);
b = new byte[FormSize];

while (true) ...{
try ...{
t = is.readByte();
b[i] = t;
i++;
} catch (EOFException e) ...{
break;
}
}
is.close();
} catch (IOException e) ...{
}
}

public boolean save() ...{
int i = 0, start1 = 0, start2 = 0;
String temp = "";
if (!flag) ...{
getByte();
flag = true;
}
try ...{
temp = new String(b, "ISO8859_1");
} catch (UnsupportedEncodingException e) ...{
return (false);
}
start1 = temp.indexOf("image/");
temp = temp.substring(start1);
start1 = temp.indexOf(" ");
temp = temp.substring(start1 + 4);
start2 = temp.indexOf("; ");
if (start2 != -1) ...{
temp = temp.substring(0, start2);
}
try ...{
byte[] img = temp.getBytes("ISO8859_1");
for (i = 0; i < img.length; i++) ...{
os.write(img[i]);
}
os.close();
} catch (IOException e) ...{
return (false);
}
return (true);
}
新的:
在通过使用FileUpload组件上传的过程中,通过自己的调试,总结如下:
1)使用之前的准备,我用的是commons-fileupload-1.1-dev.jar和commons-io-1.1-dev.jar。
解释一下:尽管有的资料解释是commons-fileupload-1.0-beta.jar和commons-beanutils.jar,通过调试的结果
显示并不是需要commons-beanutils.jar文件,而是由于在parseRequest(request)的类有关继承于DiskFileItem
类。而他有private org.apache.commons.io.output.DeferredFileOutputStream dfos。这样的就必须使用到commons-io-1.1-dev.jar。因此需要导入该包。否则就出classNotFound:.DeferredFileOutputStream的错误。
2)由于涉及文件,就涉及到文件系统。然而在java或应用服务器中对于文件系统的访问,就有一定的安全策略。
需要将下列权限添加到您应用程序服务器的安全策略文件中:
permission java.io.FilePermission "<<ALL FILES>>", "read,write,delete";
具体是添加到../bea/weblogic81/server/lib/weblogic.policy中的.
否则会可能出如下异常错误:
org.apache.commons.fileupload.FileUploadException:
java.lang.reflect.InvocationTargetException
at
org.apache.commons.fileupload.FileUpload.createItem(FileUpload.java:615)
at
org.apache.commons.fileupload.FileUpload.parseRequest(FileUpload.java:474)
at
org.apache.commons.fileupload.FileUpload.parseRequest(FileUpload.java:355)
....
3)对于不同的服务器,在调试的过程中会出各种不一样的结果。这个与具体的服务器有关。
4)由于FileUpload在不断的更新版本,它的很多方法已经不推荐使用了(这与该组件的不断的改进有关)。通过对最新的帮助文档和网上的资料写了一个标准的程序如下:
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;

/**//*
* 创建日期 2005-4-10
*
* TODO 要更改此生成的文件的模板,请转至
* 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/

/** *//**
* @author gaolong1
*
* TODO 要更改此生成的类型注释的模板,请转至 窗口 - 首选项 - Java - 代码样式 - 代码模板
*/
public class FileUpload2 extends HttpServlet ...{

/** *//**
* Destruction of the servlet. <br>
*/
private String uploadPath = "D:/addnetFile/"; // 用于存放上传文件的目录
private File tempPath = new File("D:/addnetFile/tmp/"); // 用于存放临时文件的目录

public void destroy() ...{
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/** *//**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to
* post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
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("d:/File/addnetFile/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)));
out.print(name + " " + size + "<br>");
} catch (Exception e) ...{
out.println(e);
}

} else ...{
throw new IOException("fail to upload");
}
}
}
} catch (IOException e) ...{
out.println(e);
} catch (FileUploadException e) ...{
out.println(e);
}
// 保存上传的文件到指定的目录
// 在下文中上传文件至数据库时,将对这里改写
}

/** *//**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occure
*/
public void init() throws ServletException ...{
// Put your code here
}
}
本文详细介绍 Apache FileUpload 组件的使用方法,包括文件上传到服务器的实现过程、上传文件到数据库的操作步骤以及常见问题解决方案。

被折叠的 条评论
为什么被折叠?



