SpringMVC-文件上传和下载

文件上传和下载


步骤

  • 创建maven项目,添加web支持,添加artifacts相关的库,pom.xml导入相关依赖
  • 配置web.xml 和 applicationContext.xml文件
  • 编写jsp页面,用于实现一个上传文件表单和请求
  • 编写controller,实现上传请求
  • 配置tomcat,启动测试

pom.xml

<dependencies>
	<!-- spring-mvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.1.9.RELEASE</version>
    </dependency>
	<!-- servlet -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
	<!-- jsp -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
    </dependency>
	<!-- jstl -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <!--文件-->
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>
</dependencies>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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">

    <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:applicationContext.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>

    <!-- 中文 -->
    <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>
</web-app>

applicationContext.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.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--  1. 自动扫描包,让指定包下注解生效,由IOC容器统一管理-->
    <context:component-scan base-package="com.palen.controller"/>

    <!--  2.  让springMVC不处理静态资源,类似css html js文件-->
    <mvc:default-servlet-handler/>

    <!--  3.  springMVC注解支持 : 映射器 + 适配器  并解决乱码问题 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--    <mvc:annotation-driven/>-->
    <!--  4.  添加视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>


    <!--文件上传配置-->
    <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
        <property name="maxUploadSize" value="10485760"/>
        <property name="maxInMemorySize" value="40960"/>
    </bean>
</beans>

index.jsp

<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit" value="上传">
</form>
<a href="${pageContext.request.contextPath}/download">下载</a>

FileController.java

  • 上传文件 (方法一)
//@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
//批量上传CommonsMultipartFile则为数组即可
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {

    //1.获取文件名 : file.getOriginalFilename();
    String uploadFileName = file.getOriginalFilename();

    //2.如果文件名为空,直接回到首页!
    if ("".equals(uploadFileName)){
        return "redirect:/index.jsp";
    }
    System.out.println("上传文件名 : "+uploadFileName);

    //3.上传路径保存设置:此处定为该项目的输出目录out/upload
    //path:不带文件名
    //realPath:带文件名路径
    String path = request.getServletContext().getRealPath("/upload");
    File realPath = new File(path);
    if (!realPath.exists()){//如果路径不存在,创建一个
        realPath.mkdir();
    }
    System.out.println("上传文件保存地址:"+realPath);

    //4.文件开始上传(此处雷打不动代码)
    InputStream is = file.getInputStream(); //文件输入流
    OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流

    //读取写出
    int len=0;
    byte[] buffer = new byte[1024];
    while ((len=is.read(buffer))!=-1){
        os.write(buffer,0,len);
        os.flush();
    }
    os.close();
    is.close();
    
    return "redirect:/index.jsp";
}


  • 上传文件 (方法二)
/*
     * 采用file.Transto 来保存上传的文件
     */
@RequestMapping("/upload2")
public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {

    //1.上传路径保存设置
    String path = request.getServletContext().getRealPath("/upload");
    File realPath = new File(path);
    if (!realPath.exists()){
        realPath.mkdir();
    }
    //2.上传文件地址
    System.out.println("上传文件保存地址:"+realPath);

    //3.通过CommonsMultipartFile的方法直接写文件(注意这个时候)
    file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
	
    //4.返回首页
    return "redirect:/index.jsp";
}

  • 文件下载
@RequestMapping(value="/download")
public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{
    //要下载的图片地址和名称(此处定死,可前端传来文件链接)
    String  path = request.getServletContext().getRealPath("/upload");
    String  fileName = "1.png";

    //1、设置response 响应头
    response.reset(); //设置页面不缓存,清空buffer
    response.setCharacterEncoding("UTF-8"); //字符编码
    response.setContentType("multipart/form-data"); //二进制传输数据
    //设置响应头
    response.setHeader("Content-Disposition",
                       "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));

    File file = new File(path,fileName);
    //2、 读取文件--输入流
    InputStream input=new FileInputStream(file);
    //3、 写出文件--输出流
    OutputStream out = response.getOutputStream();

    byte[] buff =new byte[1024];
    int index=0;
    //4、执行 写出操作
    while((index= input.read(buff))!= -1){
        out.write(buff, 0, index);
        out.flush();
    }
    out.close();
    input.close();
    return null;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于Spring MVC来说,文件上传下载是常见的功能之一。下面是关于如何实现文件上传下载的基本步骤: 1. 文件上传: - 在Spring MVC的配置文件中,添加`CommonsMultipartResolver`来解析文件上传请求。 - 创建一个表单页面,使用`enctype="multipart/form-data"`属性,确保可以上传文件。 - 在Controller中创建一个处理文件上传请求的方法,使用`@RequestParam("file") MultipartFile file`注解来接收文件。 - 在方法内部,可以通过`file.getInputStream()`来获取文件的输入流,进而实现上传操作。 2. 文件下载: - 在Controller中创建一个处理文件下载请求的方法。 - 在方法内部,使用`HttpServletResponse`对象设置响应头信息,包括`Content-Disposition`和`Content-Type`。 - 通过`response.getOutputStream()`获取输出流,并将文件的内容写入输出流。 需要注意的是,为了确保文件上传下载的安全性,可以进行一些额外的处理,例如限制文件类型、大小等。 以下是一个示例代码,用于演示文件上传下载: ```java @Controller public class FileController { @Autowired private ServletContext servletContext; @RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(@RequestParam("file") MultipartFile file) { try { String fileName = file.getOriginalFilename(); String filePath = servletContext.getRealPath("/uploads/") + fileName; file.transferTo(new File(filePath)); return "redirect:/success"; } catch (Exception e) { e.printStackTrace(); return "redirect:/error"; } } @RequestMapping(value = "/download", method = RequestMethod.GET) public void download(HttpServletResponse response) { try { String fileName = "example.txt"; String filePath = servletContext.getRealPath("/downloads/") + fileName; File file = new File(filePath); InputStream inputStream = new FileInputStream(file); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentType("application/octet-stream"); IOUtils.copy(inputStream, response.getOutputStream()); response.flushBuffer(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 上述代码中,`servletContext.getRealPath()`方法用于获取文件的实际路径,`IOUtils.copy()`方法用于将文件内容写入输出流。 请注意,上述示例仅为演示目的,实际应用中可能需要进行更多的异常处理、文件校验等操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值