关于上传组件,据网上专家介绍,在上传文件时Cos的性能最好,其次时FileUpload,最后为JspSmartUpload这个组件.
Cos上传的代码如下:
通过MultipartRequest实现文件的上传的信息进行封裝形成 .具体情况帮助文档.
package com.vnvtrip;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oreilly.servlet.MultipartRequest;
/**
*
* @author longgangbai
*
*/
public class FileUploadServlet extends HttpServlet {
private static String DEFAULT_COS_UPLOAD_DIR = "C://upload";
private static String DEFAULT_FILE_ENCODING_CHARSET = "UTF-8";
/**
* Constructor of the object.
*/
public FileUploadServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
}
/**
*
* 采用Cos上传文件的主要方法类
*/
@SuppressWarnings("unchecked")
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
// 存儲在创建上传文件目录
File file = new File(DEFAULT_COS_UPLOAD_DIR);
if (!file.isDirectory()) {
file.mkdirs();
}
// 上传文件总的大小
int maxPostSize = 3 * 5 * 1024 * 1024;
// response的编码为"gb2312",同时采用缺省的文件名冲突解决策略,实现上传
// 第一个参数为HttpServletRequest 第二参数: maxPostSize 上传文件大小 第三个目录上传文件目录
MultipartRequest multi = new MultipartRequest(request,
DEFAULT_COS_UPLOAD_DIR, maxPostSize,
DEFAULT_FILE_ENCODING_CHARSET);
// 输出反馈信息
Enumeration files = multi.getFileNames();
// 遍历上传的文件
while (files.hasMoreElements()) {
// 获取上传文件的對應的名称
String name = (String) files.nextElement();
System.out.println("name" + name);
// 获取名称對應的文件
File f = multi.getFile(name);
if (f != null) {
// 获取對應名称文件的路徑信息
String fileName = multi.getFilesystemName(name);
// 进行相关的数据库日志等业务操作
// ......
String lastFileName = DEFAULT_FILE_ENCODING_CHARSET
+ File.separator + fileName;
out.println("上传的文件:" + lastFileName);
}
}
}
public void init() throws ServletException {
}
}
web.xml配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>fileUpload</servlet-name>
<servlet-class>com.vnvtrip.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>fileUpload</servlet-name>
<url-pattern>/fileUpload</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
html上传的註意點同FileUpload上传(忽略).