SpringMVC上传下载

springmvc上传下载功能 参照网上代码写了一个简单的例子

1、需要导入jar包:ant.jar、commons-fileupload.jar、connom-io.jar。当然spring jar包不可缺少的哦  我这里用的是spring+springmvc+hibernate  可以到官网上直接下载springmvcjar即可

2、springmvc.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.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.2.xsd
	http://www.springframework.org/schema/mvc
	http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

<!-- 扫描包 -->
<context:component-scan base-package="com.ai.customer" />

 <!-- 启动注解 -->
 <mvc:annotation-driven />

<!-- 文件上传 -->
 <bean id="multipartResolver"
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <!-- 设置上传文件的最大尺寸为10MB -->
   <property name="maxUploadSize">
       <value>10000000</value>
   </property>
  </bean>  

<!--  静态文件访问 -->
 <mvc:default-servlet-handler/>
 <!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" >

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

</beans>

3、web.xml配置

<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath*:config/spring/spring-*.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
<filter>
    <filter-name>codeUTF-8</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>codeUTF-8</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

4、程序代码块

package com.ai.customer.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

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

import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FileUploadController {

	/*
	 * SpringMVC中的文件上传
	 * @第一步:由于SpringMVC使用的是commons-fileupload实现,故将其组件引入项目中
	 * @这里用到的是commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar
	 * @第二步:spring-mvx中配置MultipartResolver处理器。可在此加入对上传文件的属性限制
	 *  <bean id="multipartResolver"
	 *  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
	 *     <!-- 设置上传文件的最大尺寸为10MB -->
	 *        <property name="maxUploadSize">
	 *            <value>10000000</value>
	 *         </property>
	 * </bean>
	 * 第三步:在Controller的方法中添加MultipartFile参数。该参数用于接收表单中file组件的内容
	 *第四步:编写前台表单。注意enctype="multipart/form-data"以及<input type="file" name="****"/>
	 *  如果是单个文件 直接使用MultipartFile 即可
	 */ 

	/**********************上传代码**************************/
	@RequestMapping("/upload.do")
	public ModelAndView upload(String name,
			//上传多个文件
			@RequestParam("file") MultipartFile[] file,
			HttpServletRequest request) throws IllegalStateException,
			IOException {

		//获取文件 存储位置
		String realPath = request.getSession().getServletContext()
				.getRealPath("/uploadFile");

		File pathFile = new File(realPath);

		if (!pathFile.exists()) {
			//文件夹不存 创建文件
			pathFile.mkdirs();
		}
		for (MultipartFile f : file) {

			System.out.println("文件类型:"+f.getContentType());
			System.out.println("文件名称:"+f.getOriginalFilename());
			System.out.println("文件大小:"+f.getSize());
			System.out.println(".................................................");
			//将文件copy上传到服务器
			f.transferTo(new File(realPath + "/" + f.getOriginalFilename()));
			 //FileUtils.copy
		}
		//获取modelandview对象
		ModelAndView view = new ModelAndView();
		view.setViewName("redirect:index.jsp");
		return view;
	}

	/********下载代码*************/
    @RequestMapping(value = "download.do")
    public ModelAndView download(HttpServletRequest request,
            HttpServletResponse response) throws Exception {  

//        String storeName = "Spring3.xAPI_zh.chm";
    	String storeName="房地.txt";
        String contentType = "application/octet-stream";
        FileUploadController.download(request, response, storeName, contentType);
        return null;
    }  

    //文件下载 主要方法
    public static void download(HttpServletRequest request,
            HttpServletResponse response, String storeName, String contentType
           ) throws Exception {  

        request.setCharacterEncoding("UTF-8");
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;  

        //获取项目根目录
        String ctxPath = request.getSession().getServletContext()
                .getRealPath("");  

        //获取下载文件露肩
        String downLoadPath = ctxPath+"/uploadFile/"+ storeName;  

        //获取文件的长度
        long fileLength = new File(downLoadPath).length();  

        //设置文件输出类型
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment; filename="
                + new String(storeName.getBytes("utf-8"), "ISO8859-1"));
        //设置输出长度
        response.setHeader("Content-Length", String.valueOf(fileLength));
        //获取输入流
        bis = new BufferedInputStream(new FileInputStream(downLoadPath));
        //输出流
        bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        //关闭流
        bis.close();
        bos.close();
    }  

}

5、jsp页面代码 注意:设置表单中form表单的属性为:enctype="multipart/form-data"

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>

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

		<input type="text" name="name" />
		<br>
		<input type="file" name="file">
		<br>
		<input type="file" name="file" />

		<input type="submit" value="提交">
	</form>

</body>
</html>
时间: 2024-10-09 21:19:37

SpringMVC上传下载的相关文章

SpringMVC文件上传下载

不多说,代码: Spring-config.xml<!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件, 如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean --> <context:component-scan base-package="org.fkit.controller"></context:component-scan> <!-- 视图解析器 --> <be

SpringMVC文件上传下载

在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/qixiaoyizhan/p/5819392.html 今天我们来讲讲spring mvc中的文件上传和下载的几种方法. 首先附上文件目录->我们需要配置的我做了记号-> 一.文件上传 首先为了方便后续的操作,以及精简代码,我们在Utils包下封装一个文件上传下载的帮助类: Files_Helper

SSM框架-SpringMVC 实例文件上传下载

SSM框架-SpringMVC 实例文件上传下载 2017-04-17 09:38 4497人阅读 评论(6) 收藏 举报  分类: java基础(3)  目录(?)[+] 目录(?)[+] 林炳文Evankaka原创作品.转载请注明出处http://blog.csdn.net/evankaka 本文详细讲解了SpringMVC实例单文件上传.多文件上传.文件列表显示.文件下载. 本文工程免费下载 一.新建一个Web工程,导入相关的包 springmvc的包+commons-fileupload

springMVC上传与下载

springMVC上传与下载 首先,springmvc.xml必须配置: Java代码 1.      <bean id="multipartResolver" 2.              class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8"/> <bean id="m

springMVC上传和下载附件

上传: 导入需要的jar包:Spring MVC类库 + 文件上传下载需要的JAR包,图中A处为文件上传下载需要的JAR包,其余为Spring MVC类库. 构建领域模层:model层和control层.view层 FileController: 1 package com.controller.system; 2 3 import java.io.FileOutputStream; 4 import java.io.OutputStream; 5 import java.text.Simple

angularjs + springmvc 上传和下载

jsp: <form ng-submit="uploadFile()" class="form-horizontal" enctype="multipart/form-data"> <input type="file" name="file" ng-model="document.fileInput" id="file" onchange="

SpringMVC上传文件的三种解析方式

springMVC上传文件后,在action解析file文件的三种方式. jsp页面的写法: <form action="parserUploadFile1" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit"

2. SpringMVC 上传文件操作

1.创建java web项目:SpringMVCUploadDownFile 2.在项目的WebRoot下的WEB-INF的lib包下添加如下jar文件 1 com.springsource.com.mchange.v2.c3p0-0.9.1.2.jar 2 com.springsource.net.sf.cglib-2.2.0.jar 3 com.springsource.org.aopalliance-1.0.0.jar 4 com.springsource.org.apache.commo

SSM整合 上传下载之添加商品

上传下载细节: 导入xml配置文件!! 一.建表: 1 DROP TABLE IF EXISTS `t_house`; 2 CREATE TABLE `t_house` ( 3 `h_id` int(11) NOT NULL AUTO_INCREMENT, 4 `h_name` varchar(64) NOT NULL, 5 `h_rect` double(10,2) NOT NULL, 6 `h_date` date NOT NULL, 7 `h_loc1` varchar(255) NOT