栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 接收上传的附件(文件)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 接收上传的附件(文件)

protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

PrintWriter out = null;
        try {

                response.setContentType("text/html;charset=UTF-8");
                    request.setCharacterEncoding("UTF-8");

                out = response.getWriter();

                String receive_path="/files/"+UUID.randomUUID().toString() + "/";

                String suffixs =".xls.pdf.doc.docx.xlsx";

                String filepath=receiveFile( request,10, receive_path, suffixs );

                System.out.println("上传文件所在路径:"+receive_path);

                out.println(" 上传成功 ");

        } catch (Exception e) {
            e.printStackTrace();
            out.println("上传失败! " );
        } finally {
            if (out != null) {
                out.close();
            }
        }
 

}


    public static String receiveFile(HttpServletRequest request,double MAX_SIZE,String receive_path,String suffixs ) throws AppException, UnsupportedEncodingException, FileUploadException {
        // 获取表单信息
        List fileItems=getListFileItem(  request) ;
        java.util.Iterator iter = fileItems.iterator();
        String filePath ="";//导入接收文件全路径
        while (iter.hasNext()) {
            FileItem fi = iter.next();
            if (!fi.isFormField()) {//
                String filenamehz = fi.getName();// 文件名称
                if ("".equals(filenamehz) || filenamehz == null) {
                    continue;
                }
                validateFileSize(fi.getSize(),MAX_SIZE,  filenamehz);
                validateFileHz(  filenamehz,suffixs );
                validataFileExists(receive_path);
                filePath = receive_path +"/"+ filenamehz  ;
                filePath=validataFilePath(  filePath) ;
                System.out.println("导入接收文件临时全路径:"+filePath);
                receiveSaveFile(  fi,  filePath);
            }
        }
        if(filePath==null||filePath.equals("")) {
            throw new AppException("没有检测到文件!文件接收失败!");
        }
        return filePath;
    }


    public static int validateFileSize(long filesize,double MAX_SIZE,String filename) throws AppException {
        double size=getFileSize(  filesize);
        System.out.println("文件大小:"+size+"MB"+" 限制大小:"+MAX_SIZE+"MB");
        if (MAX_SIZE>0&&size> MAX_SIZE) {
            throw new AppException(" 文件:" + filename + "的尺寸超过"+MAX_SIZE+"MB,不能上传! ");
        }
        return 1;
    }


    public static double getFileSize(long filesize) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSize = df.format((double) filesize/ 1048576);// + "MB"
        if(fileSize==null||fileSize.trim().equals("")) {
            fileSize="0";
        }
        return Double.parseDouble(fileSize);
    }


    public static int validateFileHz(String filenamehz,String filetype) throws AppException {

       if(filetype==null||"".equals(filetype)) {
            return 1;
        }
        String houzhui = filenamehz.substring(filenamehz.lastIndexOf(".") + 1,filenamehz.length());
        System.out.println("文件后缀:"+houzhui);
        if(filetype.indexOf(houzhui.toLowerCase())==-1) {
            throw new AppException("文件格式异常,请重新上传!(可上传文件后缀包括:"+filetype+")");
        }
        return 1;
    }


    public static String validataFilePath(String filePath) {
        filePath=filePath.replace("\", "/");
        filePath=filePath.replace("//", "/");
        return filePath;
    }


    public static int validataFileExists(String pathdir) {
        File file = new File(  pathdir);
        if (!file.exists()  ) {// 如果文件夹不存在则创建
            file.mkdirs();
        }
        return 1;
    }


    public static int receiveSaveFile(FileItem fi,String filePath) throws AppException {
        try {
            fi.write(new File(filePath));

            fi.getOutputStream().flush();
            fi.getOutputStream().close();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                if(fi!=null&&fi.getOutputStream()!=null) {
                    fi.getOutputStream().close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            throw new AppException(e.getMessage());
        }

        return 1;
    }


    public static List getListFileItem(HttpServletRequest request) throws UnsupportedEncodingException, FileUploadException{
        request.setCharacterEncoding("GBK");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload uploader = new ServletFileUpload(factory);
        List fileItems =  uploader.parseRequest(request);
        return fileItems;
    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/571639.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号