springmvc 文件上传

springMVC 简单的文件上传 (图片或者文件)

这是controller层


import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


/**
     * 图片上传
     * @param files 传递过来的文件属性名称
     * @param request 
     * @param model
     * @return
     * @throws IOException 
     */
    @ResponseBody
    @RequestMapping( value="/threeFile",method = { RequestMethod.POST,RequestMethod.GET } )
    public String threeFileUpload( @RequestParam("files")CommonsMultipartFile files[],
            HttpServletRequest request) {

        List> resultList = new ArrayList<>();
        Map resultMap = new HashMap();
        
        // 验证文件是否相应的格式
        for (int i = 0; i < files.length; i++) {
            String fileName = files[i].getFileItem().getName();
            String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
            logger.info("--文件后缀为 : "+prefix);
            if (!TollUtil.pictureFormat(prefix)) {
                resultMap.put("error", "图片上传失败");
                resultList.add(resultMap);
                return JSON.toJSONString(resultList);
            }
        }
        
        
        List list = new ArrayList();
        // 获得项目的路径
        String path = TollUtil.getProject(request);
        logger.info("path : "+path);


        /*ServletContext sc = TollUtil.getProjects(request);
        // 上传位置  设定文件保存的目录
        String path1 = sc.getRealPath(""); //获取文件保存的目录
        logger.info("winfows path1:"+path1);*/

        String filePath = ""; //文件保存的目录

        logger.info("当前系统为: "+TollUtil.osName());
        
                // 因为Linux / 不需要转义 Windows需要转义 
        if (TollUtil.osName().trim().endsWith("Linux")) { 
            filePath = path.substring(0,path.lastIndexOf("/"));
        } else {
            filePath = path.substring(0,path.lastIndexOf("\\"));
        }

        String imgsFilePath = ConstantsUtil.imgsFilePath(filePath);
        list = FilesUtil.uploadFile(request,files,imgsFilePath);
        

        logger.info(list+"----------------");
        if (list.isEmpty()) {
            resultMap.put("error", "图片上传失败");
        } else {
            resultMap.put("sessus", list);
        }
        resultList.add(resultMap);
        return JSON.toJSONString(resultList);
    }

对应工具类 ,这里面所需要包都是jdk的

  public class ToUtil {
              
    /**
     * 验证图片后缀格式
     * @param suffixName
     * @return
     */
    public static boolean pictureFormat (String suffixName){
        if ("PNG".equalsIgnoreCase(suffixName) || "jpg".equalsIgnoreCase(suffixName) 
                || "jpeg".equalsIgnoreCase(suffixName) || "jpe".equalsIgnoreCase(suffixName) ||
                "gif".equalsIgnoreCase(suffixName)) {
            return true;
        }
        return false;
    }

    /**
     * 获取操作系统名称
     * @return
     */
    public static String osName (){
        return ConstantsUtil.OS_NAME;
    }
    
    /**
     * 生成去除-的uuid
     * @return
     */
    public static String randUUID (){
        return System.currentTimeMillis()+UUID.randomUUID().toString().replace("-", "");
    }

     /**
     * 获取项目路径 1
     * @param request
     * @return
     */
    public static String getProject(HttpServletRequest request){
        return request.getSession().getServletContext().getRealPath("");
    }

    /**
     * 获取项目路径
     * @param request
     * @return
     */
    public static ServletContext getProjects (HttpServletRequest request){
        ServletContext sc = request.getSession().getServletContext();
        return sc;
    }
      
  }

通用工具类 这里面所需要包都是jdk的

public class ConstantsUtil {

//获取操作系统名称
    public static final String OS_NAME = System.getProperties().getProperty("os.name");  
  /**
     * 返回图片显示地址
     * @param fileName
     * @return
     */
    public static String showImgsPath (String fileName){
        StringBuffer sbf = new StringBuffer();
        sbf.append("localhost:8080");
        sbf.append("/");
        sbf.append("uploadimgs");
        sbf.append("/");
        sbf.append(fileName);
        return sbf.toString();
    }
}

文件上传工具

public class FilesUtil {
    /**
     * 文件上传
     * @param request 
     * @param files 文件
     * @param path 文件保存的文件夹
     * @return
     */
    public static List uploadFile (HttpServletRequest request,
            CommonsMultipartFile files[],String path) {
        List list = new LinkedList<>();
        
        //读取上传文件的地址
        File f = new File(path);
        if (!f.exists()){
            f.mkdirs();
        }

        //图片保存的地址
        String showFilePath = ""; 
        String filePath = "";
        FileOutputStream out = null;
        InputStream in = null;
        for (int i = 0; i < files.length; i++) {
            // 获得原始文件名
            String fileName = files[i].getOriginalFilename();
            logger.info("第 "+i+" 张原始文件名" + fileName);

            // 新文件名 加上下划线可以下载时截取原文件名称
            String newFileName = TollUtil.randUUID() + "_" + fileName;

            if (!files[i].isEmpty()) {
                try {
                    filePath = path + newFileName;
                    out = new FileOutputStream(filePath);
                    in = files[i].getInputStream();
                     
                    byte buffer[] = new byte[1024];
                    int b = 0;
//                  new MultipartListenerResolver().parseRequest(request);
                    while ((b = in.read(buffer)) > 0) {
                        out.write(buffer, 0, b);
                    } 

                    showFilePath = ConstantsUtil.showImgsPath(newFileName); // 显示图片访问url 路径
                    list.add(showFilePath);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    closeUploadIO(out,in);
                }
            }
        }
        return list;
    }


    /**
     * 关闭流
     * @param fos
     * @param in
     */
    public static void closeUploadIO(FileOutputStream out,InputStream in){

        if (out != null){
            try {
                out.close();
            } catch (IOException e) {
                logger.error("FileOutputStream 关闭异常 "+e.getMessage());
            }
        }

        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error("InputStream 关闭异常 "+e.getMessage());
            }
        }

    }
}

前端页面

spring.xml 配置


    
    
        
        
        
        
        
        
        
          
    

jar包

gradle
//文件上传相关jar
    // https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload
    compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.1'
    // https://mvnrepository.com/artifact/commons-io/commons-io
    compile group: 'commons-io', name: 'commons-io', version: '2.4'

maven 

    commons-fileupload
    commons-fileupload
    1.2.1



    commons-io
    commons-io
    2.0.1



你可能感兴趣的:(springmvc 文件上传)