SpringMVC上传文件,MultiPartFile参数为空,解决方式(部分)

一、springmvc.xml(springmvc配置文件)

	<!--配置文件解析器对象-->
    <!--此处的id必须为multipartResolver,否则在控制器无法得到MultipartFile对象-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="104857600"/>
    </bean>

二、controller

	@RequestMapping("/fileupload2")
	//若没有@RequestParam("此处对应Form表单input的name属性值")
    public String fileupload2(@RequestParam("upload") MultipartFile upload) throws Exception {
     
        System.out.println("Springmvc file up load...");
        //上传位置
        // String path = request.getSession().getServletContext().getRealPath("uploads/");
        //System.out.println(path);
        //获取项目运行真实路径(tomcat 服务器bin目录)
        String realpath = System.getProperty("user.dir");
        System.out.println("realpath:"+realpath);
        //此文件夹默认在bin下
        String path = "uploads";
        File file = new File(path);
        if(file == null){
     
            System.out.println("file is null");
            return "success";
        }
        System.out.println(file.getAbsolutePath());
		//实际路径 E:\\server\\apache-tomcat-7.0.42\\bin\\uploads
        if(!file.exists()){
     
            //创建文件夹
            file.mkdir();
        }
        //说明上传文件项
        //获取上传文件名称
        if (upload == null) throw new AssertionError();
        String filename = upload.getOriginalFilename();
        //把文件名称设置为唯一值
        String uuid = UUID.randomUUID().toString().replace("-","");
        filename = uuid+"_"+filename;
        //完成文件上传
        File f = new File(path,filename);
        upload.transferTo(f);
         System.out.println(f.getAbsolutePath());
         return "success";
    }

三、Form表单

<h3>springmvc方式上传</h3>
<form action="user/fileupload2" method="post"
    enctype="multipart/form-data">
   	选择文件:<input type="file" name="upload"/> <br>
    <input type="submit" name="submit"/>
</form>

参考链接:
https://blog.csdn.net/weixin_43069201/article/details/86150950

你可能感兴趣的:(SpringMVC,java)