SpringMVC上传文件

    /**
     * 多文件上传
     * @param request
     * @param response,
     * @return pptName, sharerFileUpType
     * @throws IllegalStateException
     * @throws IOException
     */
    public static Map<String, Object> uploadListFiles(HttpServletRequest request, String filePath,boolean isUnique) throws IOException {
        Map<String, Object> map = new HashMap<>();
        //创建一个通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求  
        StringBuffer buffer = new StringBuffer();
        String localFileUrl="";
        if (multipartResolver.isMultipart(request))
        {
            //转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //取得request中的所有文件名  
            List<MultipartFile> files=multiRequest.getFiles("files");

            //MultipartFile类型的变量file在files集合范围内循环
            for(MultipartFile  file:files){
                if (file != null)
                {
                    //取得当前上传文件的文件名称  
                    String myFileName = file.getOriginalFilename();
                    //如果名称不为“”,说明该文件存在,否则说明该文件不存在  
                    if (myFileName.trim() != "")
                    {
                        //重命名上传后的文件名  
                        String fileName = file.getOriginalFilename();
                        String absPath = "D:\\media\\ddcrm\\"+filePath;
                        new File(absPath).mkdirs();
                        String path= absPath + File.separator + fileName;
                        if(isUnique){
                            String name=path.substring(0, path.lastIndexOf("."));
                            String suffix=path.substring(path.lastIndexOf("."), path.length());
                            path=name+"_"+System.currentTimeMillis()+suffix;
                        }

                        File localFile = new File(path);
                        file.transferTo(localFile);
                        localFileUrl=localFile.toString();
                        buffer.append(localFileUrl).append("@");
                    }                   
                } 
            }

        }
        String localFileUrls = buffer.toString();
        if (localFileUrls.endsWith("@"))
            localFileUrls = localFileUrls.substring(0, localFileUrls.length() - 1);
        map.put("code", 200);
        map.put("msg", "上传成功");
        map.put("localFileUrls", localFileUrls);
        return map;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值