springMVC框架的文件上传

来源:互联网 发布:信用卡淘宝退款 编辑:程序博客网 时间:2024/04/28 22:47

基于springMVC 3.X 框架的文件上传实现

1. spring使用了apache-commons下得上传组件,因此,我们需要引入两个jar包:

1. commons-fileupload.jar

2. commons-io.jar

 

3. springmvc-servlet.xml配置文件中,增加CommonsMultipartResoler配置:

 

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xmlns:mvc="http://www.springframework.org/schema/mvc"

    xmlns:p="http://www.springframework.org/schema/p"

    xmlns:context="http://www.springframework.org/schema/context"

    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="cn.bdqn.controller"/>   

    <mvc:annotation-driven /> 

 

    <!--将静态文件指定到某个特殊的文件夹中统一处理 -->

    <mvc:resources mapping="/resources/**" location="/resources/" />

    

<!-- 对转向页面的路径解析。prefix:前缀,suffix:后缀-->

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >

<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>

<property name="prefix" value="/WEB-INF/jsp/"/>

<property name="suffix" value=".jsp"/>

</bean>

<!-- 配置MultipartResolver,用于上传文件,使用springCommonsMultipartResolver -->  

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

     <property name="maxUploadSize" value="5000000"/>

     <property name="defaultEncoding" value="UTF-8"/>

    </bean>

</beans>

 

<!-- 处理文件上传配置的其他属性 -->

<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >  

    <property name="defaultEncoding" value="gbk"/> <!--默认编码 (ISO-8859-1) -->  

    <property name="maxInMemorySize" value="10240"/> <!--最大内存大小 (10240)-->  

    <property name="maxUploadSize" value="-1"/> <!--最大文件大小,-1为无限止(-1) -->  

</bean>

 

3.  建立upload.jsp页面,内容如下:

<%@ page language="java" import="java.util.*" pageEncoding=" utf-8"%>

<html>

<head>

<title>测试springmvc中上传的实现</title>

</head>

<body>

    <form action="upload"  method="post" enctype="multipart/form-data">

姓名:<input type="text" name="name" />

上传资源:<input type="file" name="attach" />

<input type="submit" value="上传"/>

</form>

</body>

</html>

 

4. 建立控制器,代码如下:

package cn.bdqn.controller;

 

import java.io.File;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.multipart.MultipartFile;

 

@Controller

public class UploadController {

@RequestMapping(value = "/upload", method = RequestMethod.POST)

public String handleUploadData(Stringname, @RequestParam MultipartFile attach, HttpServletRequest req) {

//判断文件是否为空

if(!attach.isEmpty()){

String realPath =  req.getSession().getServletContext().getRealPath("/resources/upload");

//获取文件名称

String fileName=attach.getOriginalFilename();

System.out.println(realPath+"/"+fileName);

File file = new File(realPath+"/"+fileName);

 

//获取文件类型

String fileType = fileName.substring(fileName.lastIndexOf("."));

//为避免重名,可以新建文件

File newFile=new File(realPath,new Date().getTime()+fileType);

try {

//以下三种方式都是上传文件到指定位置,可以按需选用一个

FileUtils.copyInputStreamToFile(attach.getInputStream(),file);//拷贝文件

//FileUtils.writeByteArrayToFile(newFile, attach.getBytes());//将文件重命名存储

//attach.transferTo(newFile);//快速复制文件

} catch (Exception e) {

e.printStackTrace();

}

System.out.println(attach.getName()+" ======= "+attach.getOriginalFilename()+" ====== "+attach.getContentType());

return "redirect:upload_ok.jsp";

} else {

return "redirect:upload_error.jsp";

}

}

}

 

 

5. 建立upload_ok.jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

<html>

  <head>

  </head>

  <body>

   <h1>上传成功!</h1>

  </body>

</html>

 

6. 建立upload_error.jsp页面

 <%@ page language="java" import="java.util.*" pageEncoding=" utf-8"%>

<html>

  <head>

  </head>

  <body>

   <h1>上传失败!</h1>

  </body>

</html>

 

1. 发布项目,运行测试:http://localhost:8080/springmvc03/upload.jsp

 

   进入项目发布后的目录,发现文件上传成功:

 

 

多文件上传示例代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%@taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>

<!DOCTYPE html>

<html>

<head>

<title>add</title>

</head>

<body>

<!-- 没有写action,直接提交给/add -->

<sf:form method="post" modelAttribute="user" enctype="multipart/form-data">

UserName:<sf:input path="userName"/><sf:errors path="userName"/><br/>

password:<sf:password path="password"/><sf:errors path="password"/><br/>

position:<sf:input path="position"/><br/>

email:<sf:input path="email"/><sf:errors path="email"/><br/>

Attach1:<input type="file" name="attachs"/><br/>

Attach2:<input type="file" name="attachs"/><br/>

Attach3:<input type="file" name="attachs"/><br/>

Attach4:<input type="file" name="attachs"/><br/>

<input type="submit" value="保存"/>

</sf:form>

</body>

</html>

Controller代码示例:

@RequestMapping(value="/upload",method=RequestMethod.POST)

public String add(@RequestParam("attachs") MultipartFile[] attachs,HttpServletRequest req){

String realPath =  req.getSession().getServletContext().getRealPath("/resources/upload");

for(MultipartFile attach:attachs){

if(!attach.isEmpty()){//判断文件是否为空

File file = new File(realPath+"/"+attach.getOriginalFilename());

try {

attach.transferTo(file);

} catch (Exception e) {

e.printStackTrace();

}

}

}

return "redirect:upload_ok.jsp";

}

0 0
原创粉丝点击