你可以用阿帕奇的那个组件啊,推荐你看看在通过使用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在不断的更新版本,它的很多方法已经不推荐使用了(这与该组件的不断的改进有关)。通过对最新的帮助文档和网上的资料写了一个标准的程序如下: 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 FileUpload 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 }} 对应的请求文件:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>index.html</title> <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="./servlet/FileUpload" method="post" enctype="multipart/form-data" name="form1"> <input type="file" name="file"> <input type="submit" name="Submit" value="upload"> </form> <form action="./servlet/HelloWord" method="post"> <input type="submit"/> </form> <form name="uploadform" method="POST" action="./servlet/FileUpload" ENCTYPE="multipart/form-data"> <table border="1" width="450" cellpadding="4" cellspacing="2" bordercolor="#9BD7FF"> <tr><td width="100%" colspan="2"> 文件1:<input name="x" size="40" type="file"> </td></tr> <tr><td width="100%" colspan="2"> 文件2:<input name="y" size="40" type="file"> </td></tr> <tr><td width="100%" colspan="2"> 文件3:<input name="z" size="40" type="file"> </td></tr> </table> <br/><br/> <table> <tr><td align="center"><input name="upload" type="submit" value="开始上传"/></td></tr> </table></form> </body> </html> 注:该代码部分来自网上!
客户端 文件放到 服务端 其实就是 IO的读写 先从本地读 然后写到 服务器上具体的上传 可以借助struts2的 上传
你可以百度 搜索下 struts2 上传下载 实例
HttpServletRequest request, HttpServletResponse response)
throws Exception {
Connection conn = TranStatementController.beginTransaction();
ActionForward forward = null;
Date date = new Date();
DynaActionForm fileActionForm = (DynaActionForm) form;
// FormFile用于指定存取文件的类型
FormFile file = (FormFile)fileActionForm.get("file"); // 获取当前的文件
// 获得系统的绝对路径 String dir =
// servlet.getServletContext().getRealPath("/image");
// 我上传的文件没有放在服务器上。而是存在D:D:\\loadfile\\temp\\
String dir = "D:\\loadfile\\temp\\";
String fileName = file.getFileName();
// 找到上传文件的类型的位置,这个地方的是'.'
int i = fileName.indexOf(".");
/* 截取上传文件的后缀名,此时得到了文件的类型 */
String type = fileName.substring(i + 1);
// 限制上传类型为jpg,txt,rar;
// if (!type.equals("jpg") && !type.equals("txt") && !type.equals("bmp"))// {// 当上传的类型不为上述类型时,跳转到错误页面。
if(fileName==""){
forward = mapping.findForward("error");
} else {
// 将上传时间加入文件名(这个地方的是毫秒数)
String times = String.valueOf(date.getTime());
// 组合成 time.type
String fname = times + "." + type;
// InInputStream是用以从特定的资源读取字节的方法。
InputStream streamIn = file.getInputStream(); // 创建读取用户上传文件的对象
// 得到是字节数,即byte,我们可以直接用file.getFileSize(),也可以在创建读取对象时用streamIn.available();
// int ok=streamIn.available();
int ok = file.getFileSize();
String size = null;
// 这个地方是处理上传的为M单位计算时,下一个是以kb,在下一个是byte; if (ok >= 1024 * 1024) {
float ok1 = (((float) ok) / 1024f / 1024f);
DecimalFormat myformat1 = new DecimalFormat("0.00");
size = myformat1.format(ok1) + "M";
} else if (ok > 1024 && ok <= 1024 * 1024) {
double ok2 = ((double) ok) / 1024;
DecimalFormat myformat2 = new DecimalFormat("0.00");
size = myformat2.format(ok2) + "kb";
} else if (ok < 1024) {
size = String.valueOf(ok) + "byte"; }
// 这个是io包下的上传文件类
File uploadFile = new File(dir); // 指定上传文件的位置
if (!uploadFile.exists() || uploadFile == null) { // 判断指定路径dir是否存在,不存在则创建路径
uploadFile.mkdirs();
}
// 上传的路径+文件名
String path = uploadFile.getPath() + "\\" + fname;
// OutputStream用于向某个目标写入字节的抽象类,这个地方写入目标是path,通过输出流FileOutputStream去写
OutputStream streamOut = new FileOutputStream(path);
int bytesRead = 0;
byte[] buffer = new byte[8192];
// 将数据读入byte数组的一部分,其中读入字节数的最大值是8192,读入的字节将存储到,buffer[0]到buffer[0+8190-1]的部分中
// streamIn.read方法返回的是实际读取字节数目.如果读到末尾则返回-1.如果bytesRead返回为0则表示没有读取任何字节。
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
// 写入buffer数组的一部分,从buf[0]开始写入并写入bytesRead个字节,这个write方法将发生阻塞直至字节写入完成。
streamOut.write(buffer, 0, bytesRead);
}
// 关闭输出输入流,销毁File流。
streamOut.close();
streamIn.close();
file.destroy();
// String fileSize = String.valueOf(file.getFileSize());
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fileDate = dateformat.format(date);
UserDAO dao=new UserDAO();
FileActionForm actionform =new FileActionForm(fileName,size,path,fileDate,(String)fileActionForm.get("code"),(String)fileActionForm.get("name"));
dao.addFile(actionform,conn);
TranStatementController.endTransaction(conn, true);
forward = mapping.findForward("upLoadFileResult");
}
return forward;
}
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在不断的更新版本,它的很多方法已经不推荐使用了(这与该组件的不断的改进有关)。通过对最新的帮助文档和网上的资料写了一个标准的程序如下:
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 FileUpload 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
}}
对应的请求文件:<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>index.html</title> <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="./servlet/FileUpload" method="post" enctype="multipart/form-data" name="form1">
<input type="file" name="file">
<input type="submit" name="Submit" value="upload">
</form>
<form action="./servlet/HelloWord" method="post">
<input type="submit"/>
</form>
<form name="uploadform" method="POST" action="./servlet/FileUpload" ENCTYPE="multipart/form-data"> <table border="1" width="450" cellpadding="4" cellspacing="2" bordercolor="#9BD7FF"> <tr><td width="100%" colspan="2"> 文件1:<input name="x" size="40" type="file"> </td></tr> <tr><td width="100%" colspan="2"> 文件2:<input name="y" size="40" type="file"> </td></tr> <tr><td width="100%" colspan="2"> 文件3:<input name="z" size="40" type="file"> </td></tr> </table> <br/><br/> <table> <tr><td align="center"><input name="upload" type="submit" value="开始上传"/></td></tr> </table></form> </body>
</html>
注:该代码部分来自网上!
不过现在已经很少有人去自己实现这种流数据的分析了,都是通过使用现成的实现来完成的,如今最佳的解决方案就是apache公司推出的commons-fileupload.jar包。
String path = uploadFile.getPath() + "\\" + fname;
// OutputStream用于向某个目标写入字节的抽象类,这个地方写入目标是path,通过输出流FileOutputStream去写
OutputStream streamOut = new FileOutputStream(path);
int bytesRead = 0;
byte[] buffer = new byte[8192];