Springmvc下实现多个图片文件的上传与保存

现在许多页面都开始要求实现不定量图片上传,这里给出一种利用java.MultipartFile类的方法,希望能对大家有帮助。

第一步添加jar包:在pom.xml里面添加如下代码

  
        <dependency>  
            <groupId>commons-fileuploadgroupId>  
            <artifactId>commons-fileuploadartifactId>  
            <version>1.3.1version>  
        dependency> 

然后是在配置文件applicationContext.xml中添加bean:

  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
           
         <property name="defaultEncoding" value="utf-8">property>  
           
         <property name="maxUploadSize" value="50000000">property>  
           
         <property name="maxInMemorySize" value="1024">property>  
    bean> 

这里给出前端测试界面filesTest.jsp:

"/files/test" method="post" enctype="multipart/form-data">//表示psot的内容是multipart/form-data 选择图片:type="file" name="files">

选择图片:type="file" name="files">

//这里无论几个上传按钮都ok type="submit" value="提交">

然后是后台controller:

    @Autowired
    private HttpServletRequest request;

    @RequestMapping(value = "files/test",method = RequestMethod.POST)
    @ResponseBody
    public JSONObject filesUpload(@RequestParam("files") MultipartFile[] files) //以MultipartFile类型数组形式接受传过来的图片文件
    {
        JSONObject json = new JSONObject(); 
        //判断file数组不能为空并且长度大于0
        if(files!=null&&files.length>0){
            //循环获取file数组中得文件
            for(int i = 0;i//保存文件
                saveFile(file);
            }
        }
        json.put("result","success");
        // 返回结果值
        return json;
    }

    private boolean saveFile(MultipartFile file) {
        //判断文件是否为空
        if (!file.isEmpty()){
            try {
                //文件保存路径,其中各个函数可以自行百度一下什么意思,这里我是保存到了target/helloworld目录下新建的images包内
                String filePath = request.getSession().getServletContext().getRealPath("/")+"images\\"+file.getOriginalFilename();
                //转存文件
                file.transferTo(new File(filePath));
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    //连接前端测试页面
    @RequestMapping(value = "/file/test",method = RequestMethod.GET)
    public String test(){
        return "fileTest";
    }

这样就成功实现了把多个图片文件导入到了你的项目中保存了起来。

你可能感兴趣的:(Springmvc下实现多个图片文件的上传与保存)