本文使用FileUpload组件实现文件上传,前台页面包括有普通文本和文件上传同时进行提交,后台利用了一个servlet进行处理,处理后,将状态返回到页面的一个Iframe里面.功能比较简单,只是实现了一个上传,在异常处理等方面考虑的可能不周全,希望大家指正.
FileUploadServlet.java代码:
java 代码
- package tbg.upload;
- import java.io.File;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.ArrayList;
- import java.util.List;
- 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.FileUploadException;
- import org.apache.commons.fileupload.disk.DiskFileItem;
- import org.apache.commons.fileupload.disk.DiskFileItemFactory;
- import org.apache.commons.fileupload.servlet.ServletFileUpload;
- public class FileUploadServlet extends HttpServlet {
- /**
- * 保存版本信息
- */
- private static final long serialVersionUID = 1L;
- // 默认文件上传保存路径
- public static final String UPLOAD_DIR = "/upload";
- // 默认字符集
- private static final String DEFAULT_ENCODING = "GBK";
- // 内存数据大小限制
- private int sizeThreshold = 256 * 1024;
- // request地最大值
- private long sizeMax = 256 * 1024 * 1024;
- // 单个上传文件大小限制
- private long singleSizeMax = 100 * 256 * 1024;
- // 文件临时存放路径
- private String tempDirectory = null;
- // 存放上传文件名的List
- ArrayList fileUploadList = new ArrayList();
- // 文件上传状态
- private String status = "";
- /**
- * Constructor of the object.
- */
- public FileUploadServlet() {
- super();
- }
- /**
- * Destruction of the servlet.
- */
- public void destroy() {
- super.destroy(); // Just puts "destroy" string in log
- // Put your code here
- }
- /**
- * The doGet method of the servlet.
- *
- * This method is called when a form has its tag value method equals to get.
- *
- * @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 doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doPost(request, response);
- }
- /**
- * The doPost method of the servlet.
- *
- * 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 request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html; charset=gb2312");
- PrintWriter out = null;
- boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
- if (isMultiPart) {
- processFileUpload(request, response);
- }
- out = response.getWriter();
- out.write(status);
- out.print("
"); - for (int i = 0; i < fileUploadList.size(); i++) {
- out.write((String) fileUploadList.get(i));
- out.print("
"); - }
- out.flush();
- out.close();
- fileUploadList.clear();
- }
- /**
- * Initialization of the servlet.
- *
- * @throws ServletException if an error occure
- */
- public void init() throws ServletException {
- // Put your code here
- }
- /**
- * 处理文件上传
- */
- private void processFileUpload (HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- DiskFileItemFactory factory = new DiskFileItemFactory();
- // 设置内容缓冲区,超过后写入临时文件
- factory.setSizeThreshold(sizeThreshold);
- // 得到文件临时存放地位置
- if (tempDirectory == null) {
- tempDirectory = request.getSession().getServletContext().getRealPath("/upload/temp");
- }
- // 设置文件临时存放位置
- factory.setRepository(new File(tempDirectory));
- // 设置单个文件地最大上传值
- ServletFileUpload upload = new ServletFileUpload(factory);
- // 设置字符集
- upload.setHeaderEncoding(request.getCharacterEncoding());
- // 设置单个文件上传地最大值
- upload.setFileSizeMax(singleSizeMax);
- // 设置request地最大值
- upload.setSizeMax(sizeMax);
- try {
- List items = upload.parseRequest(request);
- // 处理文件上传
- for (int i = 0; i < items.size(); i++) {
- FileItem item = (FileItem) items.get(i);
- // 保存文件
- if (!item.isFormField() && item.getName().length() > 0) {
- // 取得文件地名字
- String fileName = takeFileName(item.getName());
- // 取得文件上传路径
- String fileRealPath =
- request.getSession().getServletContext().getRealPath(UPLOAD_DIR) + File.separator + fileName;
- File uploadFile = new File(fileRealPath);
- item.write(uploadFile);
- // 更新文件上传列表
- fileUploadList.add(fileName);
- status = "上传成功";
- Thread.sleep(500);
- } else {
- String encoding = "";
- String formFieldName = "";
- // 设置字符集
- if (item instanceof DiskFileItem) {
- encoding = ((DiskFileItem) item).getCharSet();
- } else {
- encoding = request.getCharacterEncoding();
- }
- // 取得控件对应的值
- if (encoding != null) {
- formFieldName = item.getString(encoding);
- } else {
- formFieldName = item.getString(DEFAULT_ENCODING);
- }
- fileUploadList.add(formFieldName);
- }
- }
- } catch (FileUploadException e) {
- uploadExceptionHandle(request, "文件上传错误:" + e.getMessage());
- } catch (Exception e) {
- uploadExceptionHandle(request, "保存文件时错误:" + e.getMessage());
- }
- }
- /**
- * 从文件路径中取出文件名
- */
- private String takeFileName (String filePath) {
- int pos = filePath.lastIndexOf(File.separator);
- if (pos > 0) {
- return filePath.substring(pos + 1);
- } else {
- return filePath;
- }
- }
- /**
- * 上传失败处理
- */
- private void uploadExceptionHandle (HttpServletRequest request, String errMes) {
- deleteUploadFile(request);
- status = errMes;
- }
- /**
- * 删除已上传文件
- */
- private void deleteUploadFile (HttpServletRequest request) {
- for (int i = 0; i < fileUploadList.size(); i++) {
- String fileRealPath =
- request.getSession().getServletContext().getRealPath(UPLOAD_DIR)
- + File.separator + fileUploadList.get(i);
- File uploadFile = new File(fileRealPath);
- uploadFile.delete();
- }
- fileUploadList.clear();
- status = "文件已经被删除";
- }
- }
页面:uploadIndex.jsp
页面抓图
提交后:
IFrame现实的是主题 内容和文件名...