说一下利用springmvc框架弄文件上传到服务器上:
1.首先就是导入jar包(依赖):
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.3.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.0</version> <scope>provided</scope> </dependency>
<!--导入上传文件的依赖-->
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency>
2.配置我的springmvc.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--配置扫描器--> <context:component-scan base-package="com.controller"></context:component-scan> <!--视图解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--前缀--> <property name="prefix" value="/"></property> <!--后缀--> <property name="suffix" value=".jsp"></property> </bean> <mvc:annotation-driven></mvc:annotation-driven> <!--配置文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="UTF-8"></property> <property name="maxUploadSize" value="2097152"></property> //这里是文件最大的大小,可以设置 2097152就是2M
</bean> </beans>
3.然后,就是我的controller类:
4.再是我的界面:@RequestMapping("upload") public String upload(MultipartFile image, HttpServletRequest request){//在这里,我先输出一下 文件的名字+类型+大小 System.out.println(image.getOriginalFilename()); System.out.println(image.getContentType()); System.out.println(image.getSize()); //获取服务器的路径,将这个文件存到服务器上面去 String path=request.getSession().getServletContext().getRealPath("/"); File file=new File(path+"/"+image.getOriginalFilename()); try {//主要是利用FileUtils上传: FileUtils.copyInputStreamToFile(image.getInputStream(),file); } catch (IOException e) { e.printStackTrace(); } return "success"; }
<form action="/upload.action" method="post" enctype="multipart/form-data"> //记住,这个enctype是重大,一定要写的 <input type="file" name="image"/><br/> <input type="submit" value="提交"/> </form>
5.上传成功之后,就会在你项目的根目录下面有一个图片,我的就是在target文件夹的根目录下面
就这样可以完成了,关于存到数据库就很简单了包括显示也是,这里就不说了!!