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();
            }
        }
 

}

/**
     * 接收文件,并返回文件存储全路径
     * @param request http请求对象
     * @param MAX_SIZE 文件接收的大小(M)限制,<=0则不校验
     * @param receive_path 接收保存文件的绝对目录

    * @param suffixs 接收的文件后缀明(如:".zip,.rar") ,,为空则不校验文件格式
     * @return 保存接收文件的绝对全路径
     * @throws ServletException
     * @throws UnsupportedEncodingException
     * @throws FileUploadException
     */
    public static String receiveFile(HttpServletRequest request,double MAX_SIZE,String receive_path,String suffixs ) throws ServletException, UnsupportedEncodingException, FileUploadException {
        // 获取表单信息
        List<FileItem> fileItems=getListFileItem(  request) ;
        java.util.Iterator<FileItem> 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 ServletException("没有检测到文件!文件接收失败!");
        }
        return filePath;
    }

/**
     * 检测文件大小,是否超过设置值,超出则抛出异常提示
     * @param filesize 文件实际大小 单位:B
     * @param MAX_SIZE 文件大小限制 单位:MB, <0则不校验
     * @param filename 文件名
     * @return
     * @throws ServletException
     */
    public static int validateFileSize(long filesize,double MAX_SIZE,String filename) throws ServletException {
        double size=getFileSize(  filesize);
        System.out.println("文件大小:"+size+"MB"+" 限制大小:"+MAX_SIZE+"MB");
        if (MAX_SIZE>0&&size> MAX_SIZE) {
            throw new ServletException(" 文件:" + filename + "的尺寸超过"+MAX_SIZE+"MB,不能上传! ");
        }
        return 1;
    }

/**
     * 将B单位转换成MB单位,并保留两位小数
     * @param filesize
     * @return
     */
    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);
    }

/**
     * 检验文件后缀,不符合则抛出异常
     * @param filenamehz 文件名+后缀
     * @param filetype  后缀范围 如:".zip,.rar,png"
     * @return
     * @throws ServletException
     */
    public static int validateFileHz(String filenamehz,String filetype) throws ServletException {

       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 ServletException("文件格式异常,请重新上传!(可上传文件后缀包括:"+filetype+")");
        }
        return 1;
    }

/**
     * 替换文件路径分隔符为通用分隔符
     * @param filePath 文件路径
     * @return
     */
    public static String validataFilePath(String filePath) {
        filePath=filePath.replace("\\", "/");
        filePath=filePath.replace("//", "/");
        return filePath;
    }

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

/**
     * 接收保存文件
     * @param fi
     * @param filePath
     * @return
     * @throws ServletException
     */
    public static int receiveSaveFile(FileItem fi,String filePath) throws ServletException {
        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 ServletException(e.getMessage());
        }

        return 1;
    }

/**
     * 获取上传的form表单信息集合
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws FileUploadException
     */
    public static List<FileItem> getListFileItem(HttpServletRequest request) throws UnsupportedEncodingException, FileUploadException{
        request.setCharacterEncoding("GBK");
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload uploader = new ServletFileUpload(factory);
        List<FileItem> fileItems =  uploader.parseRequest(request);
        return fileItems;
    }

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时间 流逝

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值