基于SpringMVC实现的文件上传功能

        如何在用Springmvc实现文件的上传功能,在这里做一个详细的解答:

1.新建Web项目,导入相关jar包。

2.在src包下配置springmvc的配置文件springmvc.xml

    ①.配置文件头,加入context和mvc标签:

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-3.0.xsd
	http://www.springframework.org/schema/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
	">

    ②.利用context标签中的这个方法来扫描指定包下面的文件

<context:component-scan base-package="">

    ③.之后的代码:

        <mvc:annotation-driven/>
	<mvc:resources location="/pic/" mapping="/resource/*"/>
	
        /*配置视图解析器*/
	<bean id="viewResolver"
        class="org.springframework.web.servlet.view.UrlBasedViewResolver">
	    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
	   //前缀名 <property name="prefix" value="/"/>
	   //后缀名 <property name="suffix" value=".jsp"/>
	</bean>
        /*配置MultipartResolver用来处理文件上传*/
	<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	    <!-- one of the properties available; the maximum file size in bytes -->
	   //设置上传文件最大大小 <property name="maxUploadSize" value="100000"/>
	</bean>
	
</beans>

3.编写文件类,该类实现Serializable接口,私有属性:文件名,MultipartFile。获取get&set方法以及无参构造和有参构造方法。

4.配置完毕后在com.controller包下编写控制器java类

    ①.在类的前面用注解写入Controller以及RequestMapping的返回值:

@Controller
@RequestMapping("/upload")

    ②.在类中定义上传方法并同样在方法前用注解写入RequestMapping的二级返回值,在这个方法的参数列表中:

@RequestMapping("/uploadPic")
	public String uploadPic(@RequestParam("pic") MultipartFile pic,String title,HttpServletRequest request)

        @RequestParam("pic") MultipartFile pic 接收前台传过来的图片
        pic.transferTo(File file);将pic相当于copy到另外一个文件中
 

    ③.将文件上传到相应目录,构建要coye的路径,

        用getOriginalFilename()拿到文件的名字

    ④.利用MultipartFile的transferTo()方法将pic复制到另外一个文件中

    ⑤.new一个HttpSession的对象来接收request.getSession()并新建一个泛型为Photo的List集合,使用new出的session对象来获取Attribute中这个list集合(强转),如果集合为空,则新建一个ArrayList集合,并用add方法把文件加入进去。

    ⑥.使用session设置Attritube(list集合),最后返回页面名称。

5.根据自己需要编写jsp页面(如图片文件可以编写jsp页面实现展示图片的功能)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值