SpringMVC的文件上传与下载

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

一、文件上传的准备工作

1.1导入依赖

<dependencies>
        <!--springMVC-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.15</version>
        </dependency>
        <!--日志-->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.10</version>
        </dependency>
        <!--servletAPI-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <!--thymeleaf和spring整合包-->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.14.RELEASE</version>
        </dependency>
         <!--文件上传格式解析包-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>

1.2 web.xml配置

<!--SpringMVC的dispatcherservlet-->
    <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>
    <!--防止中文乱码-->
    <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>
    <!--开启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>

2.3 SpringMVC.xml 配置

 <!--开启组件扫描 包填自己的-->
    <context:component-scan base-package="com.zhao"/>
    <!--thymeleaf视图解析器-->
    <bean id="thymeleafViewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML"/>
                        <property name="characterEncoding" value="UTF-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
    <!--配置文件上传解析器,把上传文件封装为MultipartFile-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
    <!--防止静态资源过滤-->
    <mvc:default-servlet-handler/>
    <!--视图跳转-->
    <mvc:view-controller path="/" view-name="index"/>
    <mvc:view-controller path="/file" view-name="file"/>
    <!--开启mvc注解-->
    <mvc:annotation-driven>
        <!--处理中文响应乱码-->
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="defaultCharset" value="UTF-8"/>
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html</value>
                        <value>application/json</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

二、文件上传

2.1.页面

	<form th:action="@{/fileUpload}" method="post" enctype="multipart/form-data">
	    <label>文件: <input type="file" name="file"></label><br>
	    <input type="submit" value="上传">
	</form>

2.2 controller

	@PostMapping("/fileUpload")
	public String testFileUpload(MultipartFile file,HttpSession session) throws IOException {
	    //获取上传的文件名
	    String filename = file.getOriginalFilename();
	    System.out.println(filename);
	    //获取文件后缀名
	    String suffixFilName = filename.substring(filename.lastIndexOf("."));
	    //用UUID和文件后缀名作为新的文件名,防止文件名重复问题
	    filename= UUID.randomUUID().toString()+suffixFilName;
	    System.out.println(filename);
	    //判断是什么类型的文件,决定放在那个文件夹里
	    String filePath=null;
	    if (filename.contains("jpg")){
	        filePath="/static/img";
	    }else if (filename.contains("mp4")){
	        filePath="/static/mp4";
	    }
	    System.out.println(filePath);
	    //获取服务器中存放文件夹的全路径
	    ServletContext servletContext = session.getServletContext();
	    String realPath = servletContext.getRealPath(filePath);
	    System.out.println(realPath);
	    //判断存放文件夹是否存在,不存在就创建
	    File realfile = new File(realPath);
	    if (!realfile.exists()){
	        realfile.mkdir();
	    }
	    //拼接存在文件夹全路径和文件名,为文件全路径
	    filePath=realPath+ File.separator +filename;
	    System.out.println(filePath);
	    //实现上传功能
	    file.transferTo(new File(filePath));
	    return "success";
	}

根据文件的类型上传到不同的文件夹中,若初次上传则创建对应的文件夹。

二、文件下载

2.1.页面

		<a th:href="@{/fileDown/vue.js}">vue.js文件下载</a><br>
		<a th:href="@{/fileDown/1.jpg}">1.jpg文件下载</a><br>

2.2 controller

    @RequestMapping("/fileDown/{fileName}")
    public ResponseEntity<byte[]> testResponseEntity(@PathVariable("fileName") String fileName, HttpSession session) throws
            IOException {
        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取服务器中文件的真实路径
        String filePath=null;
        if (fileName.contains("jpg")){
            filePath="/static/img/"+fileName;
        }else if (fileName.endsWith("pm4")){
            filePath="/static/mp4/"+fileName;
        }
        String realPath = servletContext.getRealPath(filePath);
        System.out.println(realPath);
        //创建输入流
        InputStream is = new FileInputStream(realPath);
        //创建字节数组
        byte[] bytes = new byte[is.available()];
        //将流读到字节数组中
        is.read(bytes);
        //创建HttpHeaders对象设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();
        //设置要下载方式以及下载文件的名字
        headers.add("Content-Disposition", "attachment;filename="+fileName);
        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        //创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers,
                statusCode);
        //关闭输入流
        is.close();
        return responseEntity;
    }

根据文件的类型到不同的文件夹中下载。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值