SpringMVC实现上传下载

1.导入依赖:

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.4</version>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>

2.创建上传页面(上传,文件池,)

<form method="post" action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data">
    姓名:<input type="text" name="username">
    <p>性别:<input type="radio" name="sex" value="男">男
        <input type="radio" name="sex" value="女">女
    </p>
    <p>信息上传:<input type="file" name="photo"></p>
    <input type="submit" value="提交">

</form>
<c:forEach items="${files}" var="f">
  <p><a href="${pageContext.request.contextPath}/down/${f.name}">${f.name}</a> </p>
</c:forEach>

 3.controller中的上传下载方法

package com.openlab.controller;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import javax.swing.plaf.multi.MultiMenuItemUI;import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;


@Controller
public class UpAndDownController {


    @PostMapping("/upload")
    public String Uplo(String username,String sex,MultipartFile photo ,HttpSession session) throws Exception{
//        获得根目录
        String filepath=session.getServletContext().getRealPath("/photos");
        System.out.println(filepath);
        File file=new File("filepath");
//        判断是否存在文件夹,如果有则跳过创建,如果没有则创建
        if(!file.exists()){
            file.mkdirs();
        }
//        获得上传文件的名称
        String filename=photo.getOriginalFilename();
        System.out.println(filename);
        String files=filepath+"/"+filename;
//将文件创建后放入到指定的文件中,
            photo.transferTo(new File(files));
        return "redirect:/filepool";

    }
    @GetMapping("/filepool")
    public String filselist(HttpSession session , Map<String,Object> map){
        //获得该文件夹的绝对路径
        String filePath=session.getServletContext().getRealPath("/photos");
        File file=new File(filePath);
        //将该文件夹中的文件都放在fs文件数组中
        File[] fs=file.listFiles();
        //将数组放入到map作用域当汇中
        map.put("files",fs);
        return "filepool";
    }




    @GetMapping("/down/{filename}")
    public ResponseEntity<byte[]> down(@PathVariable("filename") String filename,HttpSession session) throws  Exception{
        String filepath=session.getServletContext().getRealPath("/photos");
        //        找到需要下载的文件,读入流中
        InputStream file=new FileInputStream(new File(filepath+"/"+filename));
//        判断流的大小并非创建byte数组的大小
        byte[] bs=new byte[file.available()];
//    将流读出
        file.read(bs);

        MultiValueMap<String,String> headers=new HttpHeaders();
        headers.add("Content-Disposition","attachment;filename="+filename);

//核心对象
        ResponseEntity entity=new ResponseEntity(bs,headers, HttpStatus.OK);
        return entity;
    }
}

4.附加(所有的配置文件)

web文件

<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">


<!--DispatcherServlet所有请求由此转发进入相应的controller-->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--初始化-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springMVC.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>


<!--拦截器请求最先到达的地方,CharacterEncodingFilter用来设置该请求的字符-->
  <filter>
    <filter-name>CharacterEncodingFilter</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>forceResponseEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>



<!--  该拦截器将会把form表单的其他方法也可以执行,例如put、delete方法-->
  <filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


</web-app>

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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--引入该会加载js、等静态文件-->
    <mvc:default-servlet-handler/>
<!--开启扫描-->
    <context:component-scan base-package="com.openlab"></context:component-scan>

<!--视图解析器,将congtroller中的返回添加前缀和后缀进行转发-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- 不会进入controller,不执行其他任务,只进行转发   -->
    <mvc:view-controller path="/" view-name="hello"></mvc:view-controller>
    <mvc:view-controller path="/userAdd" view-name="userAdd"></mvc:view-controller>
    <mvc:view-controller path="/inde" view-name="index"></mvc:view-controller>
    <mvc:view-controller path="/Up" view-name="Up"></mvc:view-controller>
    <mvc:view-controller path="/i18n" view-name="i18n"></mvc:view-controller>
    <!--此会将类中的controller设置为可进入-->
    <mvc:annotation-driven/>

<!--上传文件时需要定义的解析器,定义符号集以及最大上传大小-->
    <bean  id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="maxUploadSize" value="10240000"></property>
    </bean>
<!--国际化时需要将该设置设置,并且id名称不能随意更改-->
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="basename" value="i18n"></property>
    </bean>
<!--    将定义好的东西都放在session作用域当中-->
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"></bean>
<!--设置拦截器-->
    <mvc:interceptors>

        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"></bean>
<!--设置拦截的路径-->
       <mvc:interceptor>
<!--拦截路径-->
            <mvc:mapping path="/**"/>
<!--放任拦截路径-->
            <mvc:exclude-mapping path="/hello"/>
<!--拦截器的执行位置-->
            <bean class="com.openlab.interceptor.MyFirstInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>




</beans>

 pom文件

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>NewProjecr</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>NewProjecr Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.12</version>
      <scope>provided</scope>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.3.5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.3.5</version>
    </dependency>


    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.3.5</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjrt -->


    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjtools</artifactId>
      <version>1.9.5</version>
    </dependency>

    <dependency>
      <groupId>aopalliance</groupId>
      <artifactId>aopalliance</artifactId>
      <version>1.0</version>
    </dependency>

    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.0</version>
    </dependency>

    <dependency>
      <groupId>com.google.protobuf</groupId>
      <artifactId>protobuf-java</artifactId>
      <version>2.4.1</version>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.9</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
<!--json对象使用-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.12.1</version>
    </dependency>
    <!--文件的上传下载-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
    </dependency>










  </dependencies>

  <build>
    <finalName>NewProjecr</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值