spring mvc文件上传

31 篇文章 2 订阅

文件传输方式:

第一种方式:

Spring MVC文件上传:

  (1).利用Apache  Commons FileUpload原件进行上传;

相关元件:Commans-FileUpLoad        包的命名规则: commans-fileuload-x.y.jar

为了让其工作还需:Commans-IO        包的命名规则:commons-io-x.y.jar

  (2).Servlet3.0及其高版本的内置支持;

第二种f方式:

客户端上传


Commons FileUpload原件上传:

MutipartFile接口:

相关方法:

void transferTo(File destination)

将上传的文件保存到目的目录下

byte[] getBytes()

以字节数组的形式返回文件内容

long getSize()

以字节为单位返回文件大小

string getoRiginalFilename()

返回客户端本地驱动器的出示文件名

String getName()

以多部分的形式返回参数的名称

String getContentType()

返回文件的内容类型

inputstream getInputStream()

返回inputStream的对象,从中读取文件内容

boolean isEmpty()

判断上传的文件是否为空


实际应用:

配置部分:

1.Commans-FileUpLoad原件下载:

http://commons.apache.org/proper/commons-fileupload/

2.Commans-IO下载:

http://commons.apache.org/proper/commons-io/

3.将包拷贝到lib文件下

4.配置文件中配置:

<?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: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-4.3.xsd  
                        http://www.springframework.org/schema/context   
                       http://www.springframework.org/schema/context/spring-context-4.3.xsd  
                        http://www.springframework.org/schema/mvc   
                        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">  
    <context:component-scan base-package="controller"/>
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>
    <bean id="multipartResolver"
       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>
</beans>  

项目展示:

1.目录结构:


2.Domain类

package domain;
import java.io.Serializable;
import java.util.List;


import org.springframework.web.multipart.MultipartFile;
public class Product implements Serializable{
	private static final long serialVersionUID = 1L;
	private String name;
    private String description;
    private double price;
    private List<MultipartFile> images;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public List<MultipartFile> getImage() {
		return images;
	}
	public void setImage(List<MultipartFile> images) {
		this.images = images;
	} 
}

3.Controller类:

package controller;
import java.io.File;
import java.io.IOException;
import java.util.List;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;


import domain.Product;


@Controller
public class productController {
	private static final Log logger=LogFactory.getLog(productController.class);
	
	@RequestMapping(value="/input")
    String AddProduct(Model model){
		logger.info("nihao");
    	model.addAttribute("product", new Product());
    	return "inputProduct";
    }
	
	@RequestMapping(value="/saved")
	String saved(Model model,HttpServletRequest req,HttpServletResponse resp,
			    @ModelAttribute Product product) throws IllegalStateException, IOException {
		String name=req.getParameter("name");
		System.out.println(name);
		System.out.println(product.getName());
		
		System.out.println(product.getDescription());
		System.out.println(product.getPrice());
		//文件集合
		List<MultipartFile> files=product.getImage();
		//文件遍历转存
		 if(files!=null&&files.size()>0)
		    {
		   for (MultipartFile multipartFile : files) {
			//获取文件名
			String filename=multipartFile.getOriginalFilename();
			//设置文件对象
			File file=new File("C:\\Users\\zx\\Desktop\\C#\\image",filename);
			//进行转存
			multipartFile.transferTo(file);
		  }
		
	   }
		model.addAttribute("product", product);
		return "productInfo";
	}
}

4.配置:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  version="4.0"
  metadata-complete="true">
    <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>/WEB-INF/config/springmvc-config.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

springmvc-config.xml

<?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: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-4.3.xsd  
                        http://www.springframework.org/schema/context   
                       http://www.springframework.org/schema/context/spring-context-4.3.xsd  
                        http://www.springframework.org/schema/mvc   
                        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">  
    <context:component-scan base-package="controller"/>
    
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>
    <bean id="multipartResolver"
       class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    </bean>
</beans>  

5.JSP页面

form表单页面:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
     <form:form commandName="product" action="saved"  enctype="multipart/form-data" method="post">
     <fieldset>
     <legend>Add a Product</legend>
     <table>
     <!--名称填写  -->
     <tr>
     <td><label>name:</label></td>
     <td><form:input id="name" type="text" name="name" path="name"/></td>
     </tr>
     <!-- 产品信息 -->
     <tr>
     <td><label>description:</label></td>
     <td><form:input id="description" type="text" name="description" path="description"/></td>
     </tr>
     <!-- 产品价格 -->
     <tr>
     <td><label>price:</label></td>
     <td><form:input id="price" type="text" name="price" path="price"/></td>
     </tr>
     <!-- 产品名称 -->
     <tr>
     <td><label>image:</label></td>
     <td><input id="mul" type="file" name="image"/></td>
     </tr>
     </table>
     <input type="reset"/>
     <input type="submit"/>
     </fieldset>
     </form:form>
</body>
</html>

提交后信息:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
  <h4>The product has saved!!!</h4>
  <br/>
  Product name:${product.name }
  <br/>
  Product description:${product.description }
  <br/>
  Product price:${product.price }
  <p><img src="C:\\Users\\zx\\Desktop\\C#\\image\\110640_105916759000_2.jpg"></p>  
</body>
</html>

6.结果显示:

表单请求:


表单提交:


提交后所存储的文件:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值