美文网首页
springmvc 文件上传

springmvc 文件上传

作者: 山水风情 | 来源:发表于2017-06-08 23:56 被阅读0次

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

    <code> 这是controller层 </code>

    
    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<Map<String, Object>> resultList = new ArrayList<>();
            Map<String, Object> resultMap = new HashMap<String, Object>();
            
            // 验证文件是否相应的格式
            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<String> list = new ArrayList<String>();
            // 获得项目的路径
            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<String> uploadFile (HttpServletRequest request,
                CommonsMultipartFile files[],String path) {
            List<String> 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());
                }
            }
    
        }
    }
    

    前端页面

    <form action="/project/threeFile.do" method="post" enctype="multipart/form-data">
            <input type="file" multiple="multiple" name="files">
            <input type="submit" value="上传">
        </form>
    

    spring.xml 配置

    <!-- spring mvc做上传图片,文件小于10k就不生成临时文件了 -->
        <!-- 文件上传 -->
        <bean id="multipartResolver"
            class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <!-- maximum file size 40M -->
            <property name="maxUploadSize" value="409600000" />
            <!-- 设置在文件上传时允许写到内存中的最大值,以字节为单位计算,默认是10240 -->
            <!-- 但是经实验,上传文件大小若小于此参数,则不会生成临时文件,很尴尬,故改为1 -->
            <property name="maxInMemorySize" value="1" />
            <property name="defaultEncoding" value="UTF-8" />
            <!-- 处理上传文件的大小异常 为true -->
            <property name="resolveLazily" value="true"/>  
        </bean>
    

    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 
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.2.1</version>
    </dependency>
    
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.0.1</version>
    </dependency>
    
    
    

    相关文章

      网友评论

          本文标题:springmvc 文件上传

          本文链接:https://www.haomeiwen.com/subject/kscxqxtx.html