SpringMVC中的文件上传与下载

文件上传:

apache上传组件方案
添加依赖

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

在springmvc当中要注册一个上传解析器

<!--文件上传解析器
    id必须为multipartResolver,因为源代码中写死了
-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!--指定最大上传的大小,总上传,单位位byts-->
    <property name="maxUploadSize" value="1024*1024"/>
    <!--指定上传的编码-->
    <property name="defaultEncoding" value="UTF-8"/>
    <!--单个文件最大上传大小-->
    <property name="maxUploadSizePerFile" value="200000"/>
</bean>

准备一个上传的页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
上传成功,文件:${fileName}
</body>
</html>

后台处理

package com.xy.controller;




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 javax.net.ssl.SSLContext;
import java.io.File;
import java.io.IOException;
import java.util.Date;


@Controller
@RequestMapping("/file")
public class FileController {


    private static String  uploadPath = "F:\\IDEACode"+File.separator;




    //1,传到那里去。2,我传到哪里去。3,细节
    //入参就可以代表上传的文件
    @RequestMapping("/upload")
    public String upload(@RequestParam("file")MultipartFile multipartFile, Model model){




        //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();
                System.out.println(e.getMessage());
            }


            System.out.println(originalFilename);
        }


        return "uploadSuc";
    }
}

文件下载

后台

package com.xy.controller;


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 pathPath ="F:\\IDEACode"+ File.separator;


    @RequestMapping("/down")
    public String down(HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        //通过输出流写到客户端,浏览器


        //1,获取下载的文件名
        String fileName = "123.jpg";
        //2.构建一个文件对象
        Path path = Paths.get(pathPath, fileName);


        //3.判断他是否存在
        if(Files.exists(path)){
            //存在则下载
            //通过response设定他的响应类型
            //4,获取文件的后缀
            String fileSuffix = fileName.substring(fileName.lastIndexOf(".")+1);


            //5,设置contentType,只有指定它才能去下载
            response.setContentType("application/"+fileSuffix);


            //6,添加头信息
            try {
                response.addHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes("UTF-8"),"ISO8859-1"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }


            //7,通过path写出去
            try {
                Files.copy(path,response.getOutputStream());
            } catch (IOException e) {
                e.printStackTrace();
            }


        }


        return "msg";
    }
}

你可能感兴趣的:(Spring)