介绍一个commons—fileupload.jar这个包,以下一个例子,楼主可以进行调式用public class FileUpload extends HttpServlet {
//用于存放上传文件的目录 private String uploadPath = ""; // 用于存放临时文件的目录 private File tempPath = new File("D:\\addnetFile\\tmp\\"); public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { uploadPath = getServletConfig().getInitParameter("upload_path"); System.out.println("uploadPath=" + uploadPath); 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(tempPath); ServletFileUpload upload = new ServletFileUpload(factory); // maximum size before a FileUploadException will be thrown // 设置允许用户上传文件大小,单位:字节 upload.setSizeMax(1000000); // 物料代码 String itemNo = ""; 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(); // 正则匹配,过滤路径取文件名 // D:\\addnetFile\\item.jpg //String regExp = ".+\\\\(.+)$"; String regExp = "(.+\\.[\\w]+$)"; // 过滤掉的文件类型 String[] errorType = { ".exe", ".com", ".cgi", ".asp" }; Pattern p = Pattern.compile(regExp); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // 正常的html文件域,例如:text,radio等 if (item.isFormField()) { if (item.getFieldName().equals("itemNo")) { itemNo = item.getString(); } } // 忽略其他不是文件域的所有表单信息 if (!(item.isFormField())) { String name = item.getName(); System.out.println(name); 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(uploadPath + itemNo + ".gif")); res.sendRedirect("../basedata/item_upload.jsp?itemNo=" + itemNo); //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); } }
//用于存放上传文件的目录
private String uploadPath = ""; // 用于存放临时文件的目录
private File tempPath = new File("D:\\addnetFile\\tmp\\"); public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
uploadPath = getServletConfig().getInitParameter("upload_path");
System.out.println("uploadPath=" + uploadPath);
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(tempPath); ServletFileUpload upload = new ServletFileUpload(factory);
// maximum size before a FileUploadException will be thrown
// 设置允许用户上传文件大小,单位:字节
upload.setSizeMax(1000000);
// 物料代码
String itemNo = "";
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(); // 正则匹配,过滤路径取文件名
// D:\\addnetFile\\item.jpg
//String regExp = ".+\\\\(.+)$";
String regExp = "(.+\\.[\\w]+$)"; // 过滤掉的文件类型
String[] errorType = { ".exe", ".com", ".cgi", ".asp" };
Pattern p = Pattern.compile(regExp);
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
// 正常的html文件域,例如:text,radio等
if (item.isFormField()) {
if (item.getFieldName().equals("itemNo")) {
itemNo = item.getString();
}
}
// 忽略其他不是文件域的所有表单信息
if (!(item.isFormField())) {
String name = item.getName();
System.out.println(name);
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(uploadPath + itemNo + ".gif"));
res.sendRedirect("../basedata/item_upload.jsp?itemNo=" + itemNo);
//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);
}
}
import org.apache.struts.upload.FormFile;
/** ********* 处理文件上传 ********** */ // 获得服务器应用程序所在的绝对路径
String realPath = servlet.getServletContext().getRealPath(
servlet.getServletName());
realPath = realPath.substring(0, realPath.lastIndexOf("\\"));
String uploadPath = realPath + "\\upload\\"; // 用于存放上传文件的服务器目录绝对路径 // 创建存放头像文件目录
File uploadPathDir = new File(uploadPath);
if (!uploadPathDir.exists()) {
uploadPathDir.mkdirs();
} // 获得上传文件
FormFile file = form.getFacefile();
if (file != null) { // 判断最大文件尺寸
int fileSize = file.getFileSize();
if (fileSize >= 4194304) {
arg2.getSession().setAttribute("errormessage", "上传头像文件超过4M!");
return arg0.findForward("error");
} String fileName = file.getFileName();
// 截取文件扩展名
String expandName = fileName.substring(fileName.lastIndexOf("."),
fileName.length()); // 判断文件扩展名
if (!expandName.equalsIgnoreCase(".jpg")
&& !expandName.equalsIgnoreCase(".jpeg")
&& !expandName.equalsIgnoreCase(".bmp")
&& !expandName.equalsIgnoreCase(".gif")) {
arg2.getSession().setAttribute("errormessage",
"上传头像文件扩展名仅为: .jpg .jpeg .bmp .gif!");
return arg0.findForward("error");
} // 组成新文件名
fileName = this.getRndFilename() + expandName; InputStream inputStream = file.getInputStream();
OutputStream outputStream = new FileOutputStream(uploadPath + "/"
+ fileName); int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
outputStream.write(buffer, 0, bytesRead);
} outputStream.close();
inputStream.close(); file.destroy();
}
上传大文件不行
作好的上传组件是cos
其实你在说http协议垃圾,大文件上传是不能够用http协议来做的,它是超文本协议不是文件协议。
如果一个上传的文件上G以后,烂上传对服务器本身也是个负担。
必须要用COM实现
我就是借鉴COS的代码自己做了个文件上传的COM控件,不但一次可以上传多个文件,而且速度比COS快。还支持断点续传。
如果只是从使用角度上讲,可以从Apache网站的Common下下载FileUpload jar包。
特别注意的是,客户端的标单提交类型等的设置。具体可以看看FileUpload 原代码就懂了。对于编码,重要的不是掌握了什么知识,而是隐藏在知识背后的能力培养。一味的问一些初级的问题,以后依赖性会很高的。
fileupload有没有内存泄漏我不敢说,没具体测试过,不过到目前为止我似乎还没有碰到过fileupload的内存泄漏问题,顶多内存溢出,上传文件过大造成的,不过fileupload有避免这种内存溢出的方式,不知道你是不是使用正确了。http协议并不限制上传文件的大小,我说不适合上传大文件是因为http协议的传输机制导致的。你说我现在的技术搞不定,说实话,我是可以搞定,我又不是没有做过类似的项目,不过你说光靠java搞不定我就不太理解了,如果你不是光靠java搞定的,那你还用了什么语言呢?你辅助用了php,还是.net,还是C语言,或是别的,我就无法理解了。
至于你所说的那个什么cos或者com控件,我不知道那是什么语言实现的,我只懂java,那我就只说java,总之无论什么语言,既然你不再客户端加载富客户端技术那你就只能依赖http机制,这么想来,你也只是解析那个web浏览器发送上来的流而已,不过既然是这个东西,那么java就完全可以实现了,只不过解析过程伤脑筋一点而已。
至于支持断点传输,我不得不说你这绝对是个馊主意,首先断点传输可能会造成服务器大量垃圾,这就不说了,因为经常存在上传到一半没上传成功然后下次再上传,这样服务器不得不保留上传中断文件以便下次上传。另外,你不得不实现一个文件对比机制来判断一个用户断点前与断点后的文件是相同文件,当然这可以通过用md5的散列运算来获得上传文件的md5值与服务器保持的md5值是否相同,当然这个md5对文件的散列运算逻辑不得不房子客户端执行,如果已经上传到服务器再执行散列运输,那断点传输不是没有意义了么?这就又回到前面的话题,你不得不使用富客户端技术,那么既然使用了富客户端技术,那为什么还要用http机制呢。好了,更多问题你似乎自己也可以想明白。所以对于你漏洞百出的发言,我比较汗颜。不过那个什么cos恕我孤陋寡闻,我确实没听说过,不过在NB的东西,也要有基础支持的,你说的那些天花乱坠的东西,我觉得有点虚。