SpringMVC——文件上传、下载(异常解析器)

1.文件下载

访问资源时相应头如果没有设置 Content-Disposition,浏览器默认按照 inline 值进行处理, inline 能显示就显示,不能显示就下载.

只需要修改相应头中 Context-Disposition=”attachment;filename=文件名”

  •  attachment 以附件形式下载.
  • filename 的值就是下载时显示的下载文件名

1.1 包依赖

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
</dependency>

<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.3</version>
</dependency>

1.2 放行静态资源文件

<!--排除静态资源-->
<mvc:resources mapping="/img/**" location="/img/" />

<!-- 配置视图解析器 -->
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix" value="/WEB-INF/page/"/>
	<property name="suffix" value=".jsp"/>
</bean>

1.3  控制器

/**
 * @author zth
 * @Date 2019-07-24 22:40
 */
@Controller
public class Download {

    @RequestMapping("download")
    public void download(String fileName,HttpServletResponse response, HttpServletRequest httpServletRequest) throws IOException {
        // 设置响应头
        System.out.println(fileName);
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        OutputStream outputStream = response.getOutputStream();
        String path = httpServletRequest.getServletContext().getRealPath("img");
        System.out.println(path);
        File file = new File(path,fileName);
        byte[] bytes = FileUtils.readFileToByteArray(file);
        outputStream.write(bytes);
        outputStream.close();
    }
}

1.4 jsp

<a href="download?fileName=mao.jpg">点击下载</a>

2. 文件上传

基于 apache 的 commons-fileupload.jar 完成文件上传. 

MultipartResovler 作用:

  • 把客户端上传的文件流转换成 MutipartFile 封装类.
  • 通过 MutipartFile 封装类获取到文件流

表单数据类型分类

  • 在 <form> 的 enctype 属性控制表单类型
  • 默认值 application/x-www-form-urlencoded,普通表单数据.(少 量文字信息)
  • text/plain 大文字量时使用的类型.邮件,论文
  • multipart/form-data 表单中包含二进制文件内容.

2.1 包依赖

导入 springmvc 包和 apache 文件上传 commons-fileupload 和 commons-io 两个 jar

2.2 JSP 页面

<form action="upload" method="post" enctype="multipart/form-data"><br>
	姓名:<input type="text" name="name"/><br>
	<input type="file" name="file"><br>
	<input type="submit" value="上传"><br>
</form>

2.3 配置 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:aop="http://www.springframework.org/schema/aop" 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/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config/>
    <aop:aspectj-autoproxy />

    <!--扫描注解-->
    <context:component-scan base-package="com.zth.controller"/>
    <!--注解驱动-->
    <mvc:annotation-driven/>

    <!--排除静态资源-->
    <mvc:resources mapping="/img/**" location="/img/" />

    <!-- 配置视图解析器 -->
    <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/page/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!-- MultipartResovler解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--1204*1024-->
        <property name="maxUploadSize" value="1024"></property>
    </bean>

    <!-- 异常解析器 -->
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error</prop>
            </props>
        </property>
    </bean>

</beans>

2.4 编写控制器类

MultipartFile 对象名必须和<input type=”file”/>的 name 属性值相同

@Controller
public class Upload {
    @RequestMapping("upload")
    public String upload(MultipartFile file, String name, HttpServletRequest request) throws IOException {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        File file1 = new File(request.getServletContext().getRealPath("ups")+"/"+uuid+suffix);
        System.out.println(file1.toString());
        FileUtils.copyInputStreamToFile(file.getInputStream(),file1);
        return "hello";
    }
}

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值