用FileUpload实现文件上传

用apache的一个开源项目fileupload可以轻松的实现文件的上传,可以到apache的网站下载。

import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFile extends MappingDispatchAction ...{
    private static final int FILE_SIZE = 4194304;
    public ActionForward upload(ActionMapping mapping, ActionForm form,
            HttpServletRequest request,HttpServletResponse response) ...{
    
        try ...{
            
            DiskFileItemFactory fc = new DiskFileItemFactory();
            //设置文件的最大限度,如果超出这个限度,则将文件写入磁盘
            fc.setSizeThreshold(4000);
            //文件超过最大限度时,写入磁盘的临时路径
            fc.setRepository(new File("E:\tmp"));

            ServletFileUpload fu = new ServletFileUpload(fc);
            //设置最大文件尺寸,单位为字节,这里是4MB
            fu.setSizeMax(FILE_SIZE);
            
            //得到所有的文件:
            List fileItems = fu.parseRequest(request);
            Iterator i = fileItems.iterator();
            //依次处理每一个文件:
            while(i.hasNext()) ...{
                FileItem fi = (FileItem)i.next();
                //获得文件名,这个文件名包括路径:
                String fileName = fi.getName();
                if (fi.getSize() > FILE_SIZE)
                    throw new Exception("File is too large!");
                fileName = fileName.substring(fileName.lastIndexOf("\") + 1, fileName.length());
            
                //写入文件
                fi.write(new File("e:\tmps\" + fileName));
                
            }
        
            
        } catch (Exception e) ...{
            // TODO Auto-generated catch block
            e.printStackTrace();
            return mapping.findForward("uploadFail");
        } 

        return mapping.findForward("success");
    }
}


JSP页面代码:
<%...@ page pageEncoding="utf-8"%>

<html>
    <body>
        <form action="upload.do" method="post" enctype="multipart/form-data">
            <center>
            选择文件路径:
            <input type=file name="filename"/><br>
            <input type=submit value="上传"/>
            </center>
            
        </form>
    </body>
</html>

你可能感兴趣的:(java,apache,jsp,struts,servlet)