spring MVC 文件上传和下载

1.基本配置

(1) 导包

(2) 配置springmvc.xml

    <!-- 在 SpringMvc 配置文件中配置文件上传组件工具类 -->
    <!--id值不可更改-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 通过属性来规范上传文件的信息 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 上传文件的最大的字节数  -->
        <property name="maxUploadSize" value="5000000"></property>
    </bean>

2.上传

<form method="post" enctype="multipart/form-data" action="doUpload"> 
//上传文件必须为"post"
    <input type="text" name="name"><br>
    <input type="file" name="file"><br>
    <input type="submit" value="提交">
</form>
@RequestMapping("/doUpload")
    public String doUpload(@RequestParam(value = "file") MultipartFile[] multipartFiles) {
        //设置上传路径
        String path = "D://doUpload//";

        //没有文件夹,创建文件夹
        File file = new File(path);
        if (!file.exists()){
            file.mkdirs();
        }

        if (multipartFiles != null&&multipartFiles.length>0) {
            for (MultipartFile multipartFile : multipartFiles) {
                // 获取文件名称
                String filename = multipartFile.getOriginalFilename();
                //构建文件对象
                File file1 = new File(path + filename);

                try {

                    multipartFile.transferTo(file1);

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

3.下载 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>filter.jsp</title>
</head>
<body>

<a href="download?filename=xiazai.txt">下载</a> //拼接url

</body>
</html>
 @RequestMapping(value = "/download")
    public ResponseEntity<byte[]> download(String filename) {

        String filePath = "E://Download//";
        File file = new File(filePath + filename);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attchment", filename);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        ResponseEntity<byte[]> entity = null;
        try {
            // 利用 springMVC 的工具将指定的 File 对象中文件编译成字节数组
            entity = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return entity;
    }

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值