zoukankan      html  css  js  c++  java
  • 关于fileupload的文件上传

    package com.insigma.siis.local.pagemodel.tablesmanage;
    
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.PrintWriter;
    import java.net.URLEncoder;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    
    import org.hibernate.Query;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.jsp.PageContext;
    import javax.swing.JOptionPane;
    
    import net.sf.json.JSONObject;
    
    
    
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUploadException;
    import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
    import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    import org.apache.jasper.tagplugins.jstl.core.Out;
    import org.apache.log4j.Logger;
    import com.insigma.odin.framework.AppException;
    import com.insigma.odin.framework.persistence.HBSession;
    import com.insigma.odin.framework.persistence.HBUtil;
    import com.insigma.odin.framework.sys.file.CommonsFileUploadImp;
    import com.insigma.odin.framework.sys.file.FileUpload;
    import com.insigma.odin.framework.sys.file.FileUploadAccess;
    import com.insigma.odin.taglib.html.SysParamTag;
    import com.insigma.siis.local.business.entity.DataUpload;
    import com.insigma.siis.local.pagemodel.fileupload.DataUploadPageModel;
    
    
    
    /**
     * 文件导入通用Servlet类
     * @author jinwei
     * @date 2009-12-15
     */
    public class FileUploadServlet extends HttpServlet {
        /**
         * Logger for this class
         */
        private static final Logger logger = Logger.getLogger(FileUploadServlet.class);
    
        private String defaultBusinessName = "com.insigma.odin.framework.sys.file.DefaultFileUploadAccess";
    
        public FileUploadServlet() {
            super();
        }
    
    
        public void destroy() {
            super.destroy(); 
        }
    
    
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request,response);
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {    
            String method = request.getParameter("method");
            if(method.equals("impFileAndProcess")){
                impFileAndProcess(request,response);               
            }
            
            if(method.equals("dataUpload")){
                System.out.println("zheli");
                dataUpload(request,response);               
            }
            
        }
    
        public void init() throws ServletException {
            
        }
        
        /**
         * 导入文件,并做相关业务处理(不对Txt、Excel自动进行解析处理)
         * @param request
         * @param response
         * @throws IOException
         */
        public void impFileAndProcess(HttpServletRequest request, HttpServletResponse response) throws IOException{        
            response.setContentType("text/html");
            response.setCharacterEncoding("GBK");
            PrintWriter out = response.getWriter();
            try {
                Map<?, ?> map;   
                FileUpload upload = new CommonsFileUploadImp();//FileUpload upload = new FileUploadImp();
                String path = getServletContext().getRealPath("/");
                map = upload.upload(request,response,this.getServletConfig(),Integer.MAX_VALUE,path);
                Boolean bool = (Boolean) map.get("result");             
                List<?> list = (List<?>) map.get("filePath");
                List<?> fileNames = (List<?>) map.get("fileName");
                String className = (String)map.get("businessClass");
                String fileid = (String)map.get("fileid");
                if(className==null || className.equals("")){
                    className = defaultBusinessName; 
                }
                /********调用业务处理类***********/
                FileUploadAccess fileAccess = (FileUploadAccess)Class.forName(className).newInstance(); 
                Object rtn = fileAccess.accessAfterFileUpload((String)fileNames.get(0)+"_"+fileid, (String)list.get(0),map);
                if(bool.booleanValue()){
                    out.println("<script>parent.info(1,'"+JSONObject.fromObject(rtn).toString()+"kjdfhfhfhhf"+"');</script>");
                }else{
                    out.println("<script>parent.parent.odin.info('业务操作失败!网络发生异常导致文件无法正常传输。');parent.info(0);</script>");
                }
            } catch (AppException e) {
                logger.info("业务处理发生异常!"+e.toString());
                out.println("<script>parent.parent.odin.info('"+e.toString()+"');parent.info(0);</script>");
                e.printStackTrace();
            } catch (Exception e) {
                logger.info("调用业务类异常!"+e.toString());
                out.println("<script>parent.parent.odin.info('"+e.toString()+"');parent.info(0);</script>");
                e.printStackTrace();
            }
            out.flush();                                                     
            out.close();
        }
        
        public String getDefaultBusinessName() {
            return defaultBusinessName;
        }
    
    
        public void setDefaultBusinessName(String defaultBusinessName) {
            this.defaultBusinessName = defaultBusinessName;
        }
        
        /**
         * @author leon
         * 资料上传的方法
         * @throws IOException 
         * @throws FileUploadException 
         */
        public void dataUpload(HttpServletRequest request, HttpServletResponse response) throws IOException{
            String scategory =  request.getParameter("category");
            int category = Integer.parseInt(scategory);
            String shcode =  request.getParameter("hcode");
            int hcode = Integer.parseInt(shcode);
            response.setContentType("text/html;charset=GBK");
            String[] allowedExt = new String[] { "jpg", "jpeg", "gif", "xls","doc", "docx", "mp3", "wma", "m4a" };  
            System.out.println("开始上传");
            PrintWriter out = response.getWriter();
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //String path = getServletContext().getRealPath("/");
            String path = this.getServletConfig().getServletContext().getRealPath("/"); 
            String temp = getServletContext().getRealPath("/") + "upload/temp";   //文件上传临时存储位置
            factory.setRepository(new File(temp));
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(10*1024*1024);
            
            
            
                List<FileItem> items = null;
                try {
                    items = upload.parseRequest(request);
                } catch (FileUploadException  e1) {
                    if(e1 instanceof FileSizeLimitExceededException){
                        out.print("<script>alert('文件上传尺寸超过指定大小');</script>");
                        return;
                    }
                    e1.printStackTrace();
                }
                
                for(FileItem fi:items){
                    if(!fi.isFormField()){
                        try {
                            System.out.println("上传文件的大小:" + fi.getSize());
                            System.out.println("上传文件的类型:" + fi.getContentType());
                            // item.getName()返回上传文件在客户端的完整路径名称
                            
                            
                           
                            //得到文件后缀名
                            String name = fi.getName();
                            HBSession hb = HBUtil.getHBSession();
                            String sql = "select * from net_ae22 where name='"+name+"' and category="+category+"and flag=1 and fid="+hcode;
                            System.out.println(sql);
                            List list = hb.createSQLQuery(sql).list();
                            if(list.size() > 0){
                                out.print("<script>alert('该文件已经上传,请确认。确认要上传,请修改文件名');" +
                                        "</script>");
                                return;
                            }
    
                            String type= null;
                            if(name.length() > 0 && name != null){
                                int dot = name.lastIndexOf(".");
                                if((dot > -1)&&(dot < name.length()-1)){
                                    type=name.substring(dot+1);
                                }
                            }
                            System.out.println("上传文件的名称:" + type);
                            int allowFlag = 0;
                            for(;allowFlag < allowedExt.length; allowFlag++){
                                if(allowedExt[allowFlag].toLowerCase().equals(type.toLowerCase())){
                                    break;
                                }
                            }
                            if(allowFlag == allowedExt.length){
                                out.print("<script>alert('请上传doc,xls,jpg文件');</script>");  
                                /*for (allowFlag = 0; allowFlag < allowedExt.length; allowFlag++)  
                                    out.println("*." + allowedExt[allowFlag].toLowerCase()  
                                            + "&nbsp;&nbsp;&nbsp;"); */
                                return;
                            }
                            
                            
                            fi.write(new File(path+"/download",fi.getName()));
                            
                            
                            DataUpload du = new DataUpload();
                            du.setId( System.currentTimeMillis());
                            du.setName(fi.getName());
                            du.setType(type);
                            du.setPath(path+"download\\" + fi.getName());
                            du.setFlag(1);
                            du.setFid(hcode);
                            du.setCategory(category);
                            System.out.println(du.getPath());
                            hb.save(du);
                            hb.flush();
                            
                            
                            out.print("<script>alert('恭喜你,上传成功');" +
                                    "parent.parent.location.reload();" +
                                    "</script>");
                            //request.getRequestDispatcher("DataUpload.jsp");
                            System.out.println("上传结束");
                            
                        } catch (Exception e) {
                            e.printStackTrace();
                            System.out.println("上传出错了");
                        }
                    }
                }
        
        }
        
        /**
         * 
         * 
         * 
         */
        public HttpServletResponse download(String path,HttpServletRequest request, HttpServletResponse response) {
            try {
                // path是指欲下载的文件的路径。
                File file = new File(request.getRealPath("/")+"/"+path);
                // 取得文件名。
                String filename = file.getName();
                // 取得文件的后缀名。
                //String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
    
                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(file));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("utf-8"),"ISO-8859-1"));
                response.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return response;
        }
    }

      最近在做几个上传文件的功能,用了apache的fileupload组件。

  • 相关阅读:
    es6 学习小计
    aligin-items与aligin-content的区别
    编写Shader时的一些性能考虑
    Shader预处理宏、内置状态变量、多版本编译等
    Unity内置的shader include files
    Vertex and Fragment Shader
    对于资源上MissingScript的清理方案讨论
    Surface Shader
    LOD设置
    《蛙》
  • 原文地址:https://www.cnblogs.com/ai03/p/3049605.html
Copyright © 2011-2022 走看看