SpringMvc的文件上传和文件下载

需要引入文件上传的依赖

<!--引入文件上传依赖-->
      <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
      <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.3</version>
      </dependency>

然后在springmvc的配置文件中加入文件上传的配置

<!--配置文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <!--上传时的编码-->
        <property name="defaultEncoding" value="UTF-8"></property>

       <!--上传时的文件大小-->
        <property name="maxUploadSize" value="2097152"></property>
    </bean>

文件上传

页面上

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
<h3>文件上传</h3>
    <!--必须是post的提交-->
    <!--设置enctype的格式-->
    <form action="/filesupload.action" method="post" enctype="multipart/form-data">
        <input type="file" name="multipartFile">
        <input type="submit" value="文件上传">
    </form>
</body>
</html>

控制器中Controller

//文件上传
    @RequestMapping("filesupload")
    public String filesupload(MultipartFile multipartFile,HttpServletRequest request){
        //MultipartFile是通过apache的文件上传,用他接收文件
        //获取到文件的文件名称
        //System.out.println(multipartFile.getOriginalFilename());
        //1.先获取到upload文件夹的绝对路径
        String path=request.getRealPath("/upload");
        //2.给获取到的文件处理
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmssSSSS");
        //通过时间处理文件的前缀
        String fileName=sdf.format(new Date());
        //获取到后缀
        String exit=multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        //3.创建一个文件对象
        File file=new File(path+"/"+fileName+exit);
        //文件的复制
        try {
            FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "redirect:/filedownload.action";
    }


//查询出upload文件夹中所有的文件
    @RequestMapping("filedownload")
    public String filedownload(HttpServletRequest request){
        //获取upload里面所有的文件
        String path=request.getRealPath("/upload");
        File file=new File(path);
        File[] files=file.listFiles();
        for (File f : files) {
            System.out.println(f.getName());
        }
        request.setAttribute("files",files);
        System.out.println("成功");
        return "FileDownload";
    }

文件下载

页面中

<%@ page contentType="text/html;charset=UTF-8" isELIgnored="false" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>文件下载</title>
</head>
<body>
<h3>文件下载</h3>
        <!--获取了upload文件下的所有文件-->
        <c:forEach items="${files}" var="f">
            ${f.name}<a href="fileDownLoad.action?fileName=${f.name}">点击下载</a><br/>
        </c:forEach>
</body>
</html>

控制器中

//文件下载
    @RequestMapping("fileDownLoad")
    public ResponseEntity<byte[]> fileDownLoad(String fileName,HttpServletRequest request){//返回的是一个响应实体类,里面的类型是字节数组
        //内容
        String path=request.getRealPath("/upload");
        //获取需要下载的文件
        File file=new File(path+"/"+fileName);
        //将要下载的文件转换成字节数组
        byte[] b=null;
        try {
            InputStream is=new FileInputStream(file);//创建字节流
            b=new byte[is.available()];//获取字节流中的字节数量
            is.read(b);//读取
        } catch (Exception e) {
            e.printStackTrace();
        }

        //头部
        //创建头部的响应信息,告诉网页需要做什么操作
        HttpHeaders headers=new HttpHeaders();
        //设置要下载的文件显示的名称
        headers.setContentDispositionFormData("attchement",file.getName());
        //设置下载的时候删除的数据类型(以二进制的字节流的形式输出数据)
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //(内容,头,状态)
        ResponseEntity<byte[]> entity=new ResponseEntity<>(b,headers, HttpStatus.OK);
        System.out.println("OK");
        return entity;
    }
扫描二维码关注公众号,回复: 9547715 查看本文章
发布了62 篇原创文章 · 获赞 6 · 访问量 2583

猜你喜欢

转载自blog.csdn.net/qq_44424498/article/details/101379361