springMVC实现文件的上传下载

一、利用springMVC实现将文件上传到服务器

1,导入jar包(除了导入springMVC必须包外还需Commons-io和fileupload包)


2,配置spring.xml将该配置文件放于src下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" 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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    <!-- 配一个control的扫描器 -->
    <context:component-scan base-package="com.baojian.controller"></context:component-scan>
   <bean id="FormattingConversionServiceFactoryBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
   		<property name="converters">
   			<list>
   				<!-- 自己的日期转换器类 -->
   				<bean class="com.baojian.converter.DataConverter"></bean>
   			</list>
   		</property>
   </bean>
   <mvc:annotation-driven conversion-service="FormattingConversionServiceFactoryBean"></mvc:annotation-driven>
   <!-- 配置文件上傳解析器 -->
   
   <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   		<property name="maxUploadSize" >
     	 <value>5242880</value>
     	</property>
   </bean>
   <!-- 配置拦截器 -->
   <!-- <mvc:interceptors>
   		<mvc:interceptor>
   			<mvc:mapping path="/**"/>
   			<bean class="com.baojian.intercept.LoginIntercept"></bean>
   		</mvc:interceptor>
   </mvc:interceptors> -->
   <!-- 配置视图解析器 -->
   <!-- <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
   		视图前缀
   		<property name="prefix" value="/WEB-INF/page/"></property>
   		视图后缀
   		<property name="suffix" value=""></property>
   </bean> -->
   <mvc:resources location="images/" mapping="images/**"/>
   <mvc:resources location="js/" mapping="js/**"/>
</beans>  

3,在web.xml中配置前端控制器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>springMVC01</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <filter>
  	<filter-name>Encoding</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>
  </filter>
  <filter-mapping>
  	<filter-name>Encoding</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
    <servlet-name>hello world</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>hello world</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

4,书写控制器类

package com.baojian.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
/**
 * 这是一个相当于servlet的控制器类
 * @author ybj
 *
 */
// 表明控制器类身份的注解
@Controller
@RequestMapping("/myController")
public class MyController00 {
        // 图片上传方法,参数multiFile必须和前端上传图片时input标签的name属性一致
	@RequestMapping("/upload")
	public ModelAndView upload(HttpServletRequest request,MultipartFile multiFile) throws ServletException, IllegalStateException, IOException{
		// 创建modelAndView对象
		ModelAndView modelAndView = new ModelAndView();
		// 得到真实路径
		String realPath = getRealPath("images",request);
		// 得到新文件名
		String newName = getNewName(multiFile);
		File file = new File(realPath+"/"+newName);
		
		String imageName = "images/" + newName;
		modelAndView.addObject("imageName", imageName);
		// 上传文件
		multiFile.transferTo(file);
		System.out.println("上传成功!");
		// 跳转页面
		modelAndView.setViewName("/index.jsp");
		return modelAndView;
	}
	
	// 1,得到真实路径
	public String getRealPath(String path,HttpServletRequest request){
		String realPath = request.getServletContext().getRealPath(path);
		File file = new File(realPath);
		// 如果该文件夹不存在,创建该文件件
		if(!file.exists()){
			file.mkdirs();
		}
		return realPath;
	}
	// 2,得到新文件名的方法
	public String getNewName(MultipartFile file){
		String uuid = UUID.randomUUID().toString();
		String oldName = file.getOriginalFilename();
		String suffix = oldName.substring(oldName.lastIndexOf("."),oldName.length());
		String newName = uuid + suffix;
		return newName;
	}

}

5,书写jsp页面(Ajax异步请求遇到问题正在解决)

<%@ 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>
<script type="text/javascript" src="js/jquery-1.11.0.js"></script>
<script type="text/javascript">
	function download(){
		var conf =  confirm('你确定要下载该资源吗?');
		if(conf == true){
			
			alert("进入");
			var para ={"imagePath":"${imagePath}"};
			$.post("${pageContext.request.contextPath}/myController/download.action",para,
				function(data){
			    	alert("下载成功");
			  	}
			);
		}else{
			javascript:void(0);
		}
	}
</script>
</head>
<body>
		请选择要上传的图片:
	  <form action="${pageContext.request.contextPath}/myController/upload.action" method="post" enctype="multipart/form-data">
            <input type="file" name="multiFile" value="" /> <br /> <br /> 
            <input type="submit" value="上传" />
       </form>
        <img alt="" src="${pageContext.request.contextPath}/${imagePath}" height="200" weight="200">
        <hr>
        <font color="red">下载</font>
        <a href="${pageContext.request.contextPath}/myController/download.action?imagePath=${imagePath}" > <img alt="" src="${pageContext.request.contextPath}/${imagePath}" height="200" weight="200"/></a>
        <hr>
         <font color="red">Ajax下载</font>
         <!-- javascript:return confirm('你确定要下载该资源吗?') -->
        <img alt="" src="${pageContext.request.contextPath}/${imagePath}" height="200" weight="200" id="image" οnclick="download()"/>
</body>
</html>
二、文件下载

实现文件下载主要注意设置response.setHeader( "Content-Disposition", "attachment;filename=" + fileName); 设置图片以附件形式打开。在控制器类中添加下载方法

        // 下载标准方法的写法
	@RequestMapping(value="/download",method=RequestMethod.POST)
	public ModelAndView download(HttpServletRequest request,HttpServletResponse response,String imagePath) throws ServletException, IllegalStateException, IOException{
		// 创建modelAndView对象
		ModelAndView modelAndView = new ModelAndView();
		// 获取服务器的真实路径
		String realPath = getRealPath(imagePath, request);
		// 获取文件名
		String fileName = imagePath.substring(imagePath.indexOf("/") + 1, imagePath.length());
		// 设置相应头部信息
		// response.setHeader("Content-Disposition", "attachment;fileName" + fileName);
		response.setHeader( "Content-Disposition", "attachment;filename=" + fileName); 
		// 获取输出流
		OutputStream output = response.getOutputStream();
		// 根据真实路径创建输入流对象
		FileInputStream input = new FileInputStream(realPath);
		IOUtils.copy(input, output);
		System.out.println("download success!");
		return modelAndView;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值