springmvc上传与下载

发布时间:2024年01月18日

文件上传

结构图

在这里插入图片描述

导入依赖

<dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.8.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
    </dependency>

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>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <filter>
    <filter-name>encodingFilter</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>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

上传一个或多个文件

index.jsp代码

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" action="file" enctype="multipart/form-data">

    上传文件:<input type="file" name="picture">

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

<hr>
<h1>多文件</h1>
<form method="post" action="files" enctype="multipart/form-data">

    上传文件1:<input type="file" name="pictures">
    上传文件2:<input type="file" name="pictures">
    上传文件3:<input type="file" name="pictures">

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

WEB-INF下的success.jsp代码

在这里插入图片描述

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

    <context:component-scan base-package="com.tmg"></context:component-scan>
<!--    视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
<!--    静态资源处理器-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>
<!--    注解驱动-->
    <mvc:annotation-driven></mvc:annotation-driven>
<!--    文件上传处理器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="maxUploadSize" value="10485760"></property>
    </bean>
</beans>

FileController代码

运行的时候,浏览器页面要在WEB-INF下的index.jsp,跑完该项目时,页面是webapp下的index.jsp,所以跑完之后切换请求路径(/toFile)进入WEB-INF下的index.jsp

package com.tmg.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
public class FileController {
    private static final String DIR = "D:\\picture\\";

    @RequestMapping("/toFile")
    public String text() {

        return "/index";
    }

    @RequestMapping("file")
    public String text1(MultipartFile picture) throws IOException {
        String filename = picture.getOriginalFilename();
        picture.transferTo(new File(DIR, filename));
        return "success";
    }

    @RequestMapping("/files")
    public String text2(MultipartFile[] pictures) {

        try {
            for (MultipartFile picture : pictures) {
                String filename = picture.getOriginalFilename();

                if("".equals(filename)){
                    continue;
                }
                picture.transferTo(new File(DIR, filename));
                System.out.println(filename);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            return "success";
        }
    }

}

文件下载

DownloadController代码

跑的时候记得在路径带上 file=XXX ,并在执行前指定自己下载目录

package com.tmg.controller;

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

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

/**
 * 下载控制器
 */
@Controller
public class DownloadController {

    @RequestMapping("/download")
    public void download(String file,  HttpServletResponse response) throws IOException {
        //下载文件的路径
        String path = "D:\\picture\\";
        File downFile = new File(path+file);
        if(downFile.exists()){
            //设置浏览器下载内容类型,响应头
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition","attachment;filename="+file);
            //通过流发送文件
            Files.copy(downFile.toPath(),response.getOutputStream());
        }
    }
}

文章来源:https://blog.csdn.net/weixin_57689217/article/details/135091656
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。