在很多的jsp 项目中,我们要上传附件,如很多的BBS也有这样的功能,邮件也一样,相信大家已非常熟悉了,这里就介绍他是怎么实现的;
这里我们选择第三方组件,你可以选择:commons-fileupload 或jspSmartUpload
这里我们选择apache的commons-fileupload;
这个组件的包你可以在:http://jakarta.apache.org/site/downloads/下载
可以在左边的导航中找到Commons然后在里面找到commons-fileupload
在用这个包的同时我们还用到了apache的io包,它同样在Commons里可以找到;
下面是书上的一个实例代码:
upload.jsp
<%@ page language="java" contentType="text/html;charset=GBK"
pageEncoding="GBK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<title>Insert title here</title>
</head>
<body>
common file upload 上传实例<br>
<form method="post" action="FileUpload" ENCTYPE="multipart/form-data">
文件:<input type="file" name="file"/>
<input type="submit" value="上传" name="submit">
</form>
</body>
</html>
下面是一个处理的servlet
FileUpload.java
package servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileUpload() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart=ServletFileUpload.isMultipartContent(request);
if(isMultipart){
FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload upload=new ServletFileUpload(factory);
Iterator items;
try{
items=upload.parseRequest(request).iterator();
while(items.hasNext()){
FileItem item=(FileItem)items.next();
if(!item.isFormField()){
String name=item.getName();
String fileName=name.substring(name.lastIndexOf('\\')+1, name.length());
String path=request.getRealPath("file")+
File.separatorChar+fileName;
File uploadFile=new File(path);
item.write(uploadFile);
response.setContentType("text/html");
response.setCharacterEncoding("gb2312");
PrintWriter out=response.getWriter();
out.print("<font size='12'>上传文件为"+name+"<br>");
out.print("保存地址为"+path+"<br>");
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
}