jsp中的文件上传

  首先需要有以下的jar包

  jsp代码如下:

<!-- ${pageContext.request.contextPath}为: "/" + 当前项目名   -->
    <form action="${pageContext.request.contextPath}/upLoad" method="post"  enctype="multipart/form-data">
        <p><label for="picture">图片:</label><input type="file" name="picture"/></p>
        <p><label for="picture">图片:</label><input type="file" name="picture"/></p>
        <p><input type="submit" value="上传"/></p>
    </form>

   使用文件上传必须使用POST方式进行上传,以及添加enctype属性

控制器代码如下

@RequestMapping(value= {"upLoad"})
    public String upLoad(@RequestParam(value="picture",required=false) MultipartFile[]  picture,
            HttpServletRequest request) {
        //获取服务器上传地址
        String path = request.getRealPath(File.separator)+"myupload";
        if(picture.length>0&&picture!=null) {
            for (MultipartFile p : picture) {
                if (p.isEmpty()) {     
                    break;
                }
                //获取文件名
                String oldFileName =p.getOriginalFilename();
                //获取后缀
                String suffix = oldFileName.substring(oldFileName.lastIndexOf(".")+1, oldFileName.length());
                //设置随机名称  防止覆盖同名文件
                String fileName = UUID.randomUUID().toString().replaceAll("-", "")+"."+suffix;
                System.err.println(fileName);
                //根据 路径符串,名字符串创建一个新 File实例。 
                File targetFile = new File(path,fileName);
                try {
                    //transferto()方法,是springmvc封装的方法,用于图片上传时,把内存中图片写入磁盘
                    p.transferTo(targetFile);  
                    System.err.println("成功!");
                    log.debug("文件上传成功");
                }catch (Exception e) {
                    e.printStackTrace();
                    log.error("文件上传失败: "+e.getMessage());
                }
            }
        }else {
            System.err.println("失败!");
        }
        return "success";
    }

 此时可以上传之后可以再增加一些条件,如判断文件的类型,文件夹是否存在等,如下

     if(!Arrays.asList("jpg","png","jpeg","pneg").contains(suffix)) {
                  System.out.println("图片格式错误必须是jpg,PNG,JPEG,pneg其中一种");
                 return "error";
         }
         if(!targetFile.exists()) {
                 targetFile.mkdirs();//如果路径不存在,就创建该目录
         }
原文地址:https://www.cnblogs.com/hfx123/p/9796670.html