SpringMVC文件上传

图片上传处理

1.配置虚拟路径

<!--
在tomcat上配置图片虚拟目录,在tomcat下conf/server.xml中添加:
  <Context docBase="D:main" path="/img"></Context>
访问http://localhost:8080/img即可访问C:img下的图片。 
--> 

2.加入文件上传jar包

实现图片上传需要加入的jar包:
commons-fileupload-1.2.2.jar
commons-io-2.2.jar 

3.配置上传解析器

<!-- 需要配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 配置文件上传大小(字节) -->
    <property name="maxUploadSize" value="5000000"></property>
</bean> 

4.jsp页面修改

//表单上传文件  方法改为post  enctype改为multipart/form-data
<form action="${pageContext.request.contextPath }/upload.html" method="post" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="submit" value="上传">
</form> 

5.图片上传

@RequestMapping("/upload.html")
    public String upload(MultipartFile file, Model model){
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(),new File("D:/main/",file.getOriginalFilename()));
            model.addAttribute("msg","上传成功");
        }catch (IOException e){
            e.getMessage();
            model.addAttribute("msg","上传失败");
        }
        return "index";
    }
原文地址:https://www.cnblogs.com/a77355699/p/8082207.html