Springmvc 文件上传与下载教程

文件上传

apache 上传组件方案

1 添加依赖

 
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
​

2 在springmvc单中要注册一个文件上传解析器

<!--文件上传解析器
        id必须是multipartResolver,原因是源代码里面写死为这个名字
    -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--定义文件最大传输的大小 总的  单位为 bytes -->
    <property name="maxUploadSize" value="1024000"/>
    <!--指定上传的编码-->
    <property name="defaultEncoding" value="UTF-8"/>
    <!--单个文件最大传输大小-->
    <property name="maxUploadSizePerFile"  value="2000000"/>
</bean>
 

3 准备上传的页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/9/3
  Time: 8:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--添加一个 enctype="multipart/form-data" --%>
<form action="${ctx}/file/upload" method="post" enctype="multipart/form-data">
    文件:<input type="file"  name="file"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>
​

 

4 后台处理程序

package com.sz.constant;
​
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
​
import java.io.File;
import java.io.IOException;
import java.util.Date;
​
@Controller
@RequestMapping("/file")
public class FileController {
​
    private static String uploadPath  = "E:" + File.separator;
​
​
​
    // 入参就可以代表上传的文件
    @RequestMapping("/upload")
    public String upload(@RequestParam("file")MultipartFile multipartFile, Model model){
        // 1 传输地址 2 传输的文件, 3传输的细节
​
        // 1 判断
        if(multipartFile != null && !multipartFile.isEmpty()){
            // 验证是否为空
            // 2 获取原始的文件名
            String originalFilename = multipartFile.getOriginalFilename();
​
            // 3 先截取原文件的文件名前缀,不带后缀
            String fileNamePrefix = originalFilename.substring(0,originalFilename.lastIndexOf("."));
​
            // 4 加工处理文件名,将原文件名+时间戳
            String newFileNamePrefix = fileNamePrefix +new Date().getTime();
​
            // 5 得到新文件名
            String newFileName = newFileNamePrefix + originalFilename.substring(originalFilename.lastIndexOf("."));
​
            // 6 构建文件对象
            File file = new File(uploadPath + newFileName);
​
            // 7 上传
            try {
                multipartFile.transferTo(file);
                model.addAttribute("fileName",newFileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
​
        }
​
        return "uploadSuc";
    }
}
​

 

servlet3.0新特性

<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
​
</bean>
servlet定义

<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>
    <multipart-config>
        <max-file-size>200000000</max-file-size>
    </multipart-config>
</servlet>

 

文件下载

 

package com.sz.constant;
​
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
​
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
​
@Controller
@RequestMapping("/download")
public class DownloadController {
​
    // 定义一个文件下载的目录
    private static String parentPath = "E:" + File.separator;
​
    @RequestMapping("/down")
    public String down(HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        // 通过输出流写到客户端,浏览器
        // 1 获取文件下载名
        String fileName = "爱与痛的边缘.mp4";
​
        // 2 构建一个文件对象通过Paths工具类获取一个Path对象
​
        Path path = Paths.get(parentPath, fileName);
​
        // 3 判断它是否存在
        if(Files.exists(path)){
            // 存在则下载
            //  通过response设定它的响应的类型
            // 4 获取文件的后缀
            String fileSuffix = fileName.substring(fileName.lastIndexOf(".")+1);
​
            // 5 添加头信息
​
            // 6 设置contentType,只有制定它才能去下载
            response.setContentType("application/"+fileSuffix);
​
            //文件字符流转换 设置编码格式 ISO8859-1
            try {
                response.addHeader("Content-Disposition","attachment; filename="+new String(fileName.getBytes("UTF-8"),"ISO8859-1"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            // 7 文件的copy()方法 响应文件传输到设置的文件路径
            try {
                Files.copy(path,response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
​
        return  "msg";
​
    }
}
​

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值