下载两个第三方开发包: commons-fileupload 和 commons-io(被commons-fileupload引用).
官方下载:
commons-fileupload-1.2.jar
http://commons.apache.org/downloads/download_fileupload.cgi
commons-io-1.3.2
http://commons.apache.org/downloads/download_io.cgi
Portlet相关代码:
页面JSP代码:
需要注意的地方:
1.
对于Portlet:
import org.apache.commons.fileupload.portlet.PortletFileUpload;
dfif.setRepository(new File(portletContext.getRealPath("/UploadFileTemp")));
String u_name = portletContext.getRealPath("/") + "/UploadFile/" + prefix + "." + t_ext;
如果是一般的J2EE Web工程,就需要对上面各点做如下修改:
import org.apache.commons.fileupload.servlet.ServletFileUpload;
dfif.setRepository(new File(request.getRealPath("/") + "UploadFileTemp")));
String u_name = request.getRealPath("/") + " UploadFile /" + prefix + "." + t_ext;
打开commons-fileupload-1.2.jar,你会发现它已经包含了PortletRequest和ServletRequest的相应处理
org.apache.commons.fileupload.portlet
org.apache.commons.fileupload.servlet
方便Portal和Web Project的开发。
2.
对于方法 .getRealPath(String path)的使用需要特别注意。当你所指向的文件夹或文件是存在于.ear或者.war中时,此方法不会返回其绝对路径,而是返回null。
这个时候,你需要将你的.ear或者.war使用Java的 jar xvf *.ear命令解压开安装到相应的Web Server。或者将自己想存放的路径指向Server的其他路径。
getRealPath
java.lang.String getRealPath(java.lang.String path)
Returns a String containing the real path for a given virtual path. For example, the path /index.html returns the absolute file path of the portlet container file system.
The real path returned will be in a form appropriate to the computer and operating system on which the portlet container is running, including the proper path separators. This method returns null if the portlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).
Parameters:
path - a String specifying a virtual path
Returns:
a String specifying the real path, or null if the transformation cannot be performed.