SpringMVC文件上传及下载

文件上传

准备Jar包

  <dependencies>
  
 <!-- Spring MVC 及 Spring系列包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.24.RELEASE</version>
    </dependency>
    
    <!--Servlet核心-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>
    
    <!-- JSTL -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!--SpringMVC文件上传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>
  </dependencies>

准备好上述jar包,并将jar导入进创建好的项目中

准备一个前端页面,我们可以把Web项目中的index.jsp作为我们的前端页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>

<form action="" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit" value="upload"/>
</form>

</body>
</html>

因为我们还没有编写controller,所以action处的请求我们先空着

编写Web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">
  
  <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:</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>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>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

因为我们还没有编写servletmvc.xml 所以我们的DispatcherServlet中的classpath先空下来。

编写servletmvc.xml配置文件

首先在java目录下创建一个controller目录,并且在WEB-INF目录下创建一个jsp目录。

<?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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        https://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.westos.controller"/>

    <mvc:default-servlet-handler/>

    <mvc:annotation-driven/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    <bean id="multipartFile" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8"/>
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>
    
</beans>

之后我们回到编写web.xml中 将classpath: 的值写为我们的springmvc配置文件

<param-value>classpath:springmvc-serlvet.xml</param-value>

编写FileUploadController

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Controller
public class FileUploadController {

    @RequestMapping("/upload")
    @ResponseBody
    public String FileUpload(@RequestParam("file")CommonsMultipartFile file, HttpServletRequest request) throws IOException {

        String filename = file.getOriginalFilename();
        if("".equals(filename)){
            return "fail";
        }
        System.out.println("文件名字"+filename);

        String path = request.getServletContext().getRealPath("/upload");

        File realpath = new File(path);
        if(!realpath.exists()){
            realpath.mkdir();
        }

        System.out.println("文件上传地址"+realpath);

        InputStream inputStream = file.getInputStream();
        FileOutputStream outputStream = new FileOutputStream(new File(realpath, filename));

        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len=inputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();
        return "success";
    }
}

我们回到前端页面,填写action

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

项目结构:
在这里插入图片描述

文件下载

我们继续以上述的项目为例

首先我们要先编写Controller,我们可以在之前的Controller中增加一个方法就可以了

我们在桌面上找一张图片,作为要下载的图片,图片的名字为111.jpg

 @RequestMapping("/download")
    public String FileDownload(HttpServletResponse response) throws IOException {
        //桌面的路径
        String path = "C:\\Users\\Administrator\\Desktop\\";
        //要下载的文件名字
        String fileName = "111.jpg";

        response.reset();//设置页面不换缓存
        response.setCharacterEncoding("utf-8");//设置字符编码
        response.setContentType("mutipart/form-data");//二进制传输数据

        //设置响应头
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
        File file = new File(path, fileName);
        FileInputStream InputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len=InputStream.read(bytes))!=-1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
            outputStream.close();
            InputStream.close();
            return null;

    }

编写前端页面

<a href="${pageContext.request.contextPath}/download">下载图片</a>

结果如图:
在这里插入图片描述

上传文件的第二种方式,使用file.Transto

我们只需要将本项目中的Controller的文件上传方法重新编写即可

@RequestMapping("/upload")
    @ResponseBody
    public String FileUpload(@RequestParam("file")CommonsMultipartFile file,HttpServletRequest request) throws IOException {

        String path = request.getServletContext().getRealPath("/upload");
        File realpath = new File(path);
        if(!realpath.exists()){
            realpath.exists();
        }

        file.transferTo(new File(realpath+"/"+file.getOriginalFilename()));

        return "success";

    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值