SpringBoot下搭建SSM框架开发web网站(四)

2019-11-05  本文已影响0人  我想放假休息

文件的上传与下载

springBoot自身加载了MultipartServletResolver解析器,无须引入commons-io.jar , commons-fileupload.jar这两个jar包,如果不是在SpringBoot下则需要导这两个包。

1、文件上传

先写个简陋的 html 上传页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>
<!--文件上传的表单的提交方式必须是post-->
<form action="fileUploadController" method="post" enctype="multipart/form-data">
    上传文件 <input type="file" name="filename"/><br/>
    <input type="submit">
</form>
</body>
</html>

为了方便观看和理解,我就一个控制类就写一个类,下面是文件上传的控制方法

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * SPringBoot文件上传
 */
@Controller
public class fileUploadController {
    /**
     * 处理文件上传
     */
    @ResponseBody
    @RequestMapping("/fileUploadController")
    public Map<String,Object> fileUpload(MultipartFile filename) throws Exception{
        System.out.println(filename.getOriginalFilename());//打印文件上传名称
        filename.transferTo(new File("e:/"+filename.getOriginalFilename()));//文件保存
        Map<String,Object> map=new HashMap<>();
        map.put("msg","ok");
        return map;
    }
}

2、文件下载

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class fileDownlaodController {
    @RequestMapping("/download")
    public String downLoad(HttpServletResponse response,String name) throws UnsupportedEncodingException {
        String filePath = "E:" ;  //文件存在的目录
        File file = new File(filePath + "/" + name);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            // response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(name,"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download---" + name);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
}

然后在地址栏输入127.0.0.1/download?name=aaaa.m4a就可以下载 aaaa.m4a 了。

当然,我们也可以通过配置application.properties对SpringBoot上传的文件进行限定默认为如下配置:

spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=0
spring.servlet.multipart.location=
spring.servlet.multipart.max-file-size=1MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.resolve-lazily=false

enabled默认为true,既允许附件上传。
file-size-threshold限定了当上传文件超过一定长度时,就先写到临时文件里。有助于上传文件不占用过多的内存,单位是MB或KB,默认0,既不限定阈值。
location指的是临时文件的存放目录,如果不设定,则web服务器提供一个临时目录。
max-file-size属性指定了单个文件的最大长度,默认1MB,max-request-size属性说明单次HTTP请求上传的最大长度,默认10MB.
resolve-lazily表示当文件和参数被访问的时候再被解析成文件。
上一篇下一篇

猜你喜欢

热点阅读