SpringBoot系列:实现文件上传和下载

一.引入jar包

   <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

二.单文件上传

这里文件上传保存路径可以先把路径存到redis缓存中,在下载文件的时候获取文件路径

  /**
     * 单文件上传
     *
     */
    @RequestMapping("/upload")
    @ResponseBody
    public  String uploadFile(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        //判断文件是否为空
        if (multipartFile.isEmpty()) {
            return "File is not Empty!!";
        }
        //获取文件名
        String filename = multipartFile.getOriginalFilename();
        System.out.println("文件名:"+filename);
        //获取文件后缀名,进行判断选择要上传的文件类型
        String suffixName = filename.substring(filename.lastIndexOf("."));
        System.out.println("后缀名:"+suffixName);
        //设置存放根路径,可以设置任意存放位置,这里默认存放服务端根目录
        String contextPath = request.getServletContext().getRealPath("/res/imgs/");
        System.out.println(contextPath);
        File file=new File(contextPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        //存放数据
        File targetFile = new File(contextPath + filename);
       //把文件路径存放在缓存中
        redisTemplate.opsForValue().set("file",contextPath + filename);
        try {
            multipartFile.transferTo(targetFile);
            return "Success !!!";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Failure !!!";

}

三.多文件上传

/**
     * 多文件上传
     */
    @RequestMapping("/manyUp")
    public String mannyUploadFile(MultipartHttpServletRequest request) throws IOException {
        //获取上传路径
        String realPath = request.getServletContext().getRealPath("/res/imgs/");
        //创建文件夹
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdirs();
        }
//        获取多个文件的map实例
        Map<String, MultipartFile> fileMap = request.getFileMap();
        Set<String> strings = fileMap.keySet();
        for (String key:strings) {
            //获取multipartFile 实例
            MultipartFile multipartFile = fileMap.get(key);
            //获取文件名
            String filename = multipartFile.getOriginalFilename();
            System.out.println("文件名:"+filename);
            //上传文件
            multipartFile.transferTo(new File(realPath+filename));
        }
        return "Suceess !!!";
    }

四.文件下载

用户点击了下载链接之后,首先服务器设置一下参数,然后使用输出输出流将制定路径下的文件进行输出。

 /**
     * 文件下载
     */
    @RequestMapping("/downLoad")
    @ResponseBody
    public  String downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
//        String filename="2.xlsx";
//        String filePath = "D:/download" ;
        File file = new File((String) redisTemplate.opsForValue().get("file"));
        String filename = file.getName();
        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(filename,"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) {
                e.printStackTrace();
            }
            System.out.println("----------file download---" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "Success !!";

    }

五.测试

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<form action="http://localhost:8080/demo/upload" method="post" enctype="multipart/form-data">
		    文件选择:
			<input type="file" name="file">
		    <input type="submit">
		</form>
		
		
		<p>文件下载</p>
		<form action="http://localhost:8080/demo/downLoad" method="post">
			<p><h2>1.png</h2></p>
			下载:<input type="submit" />
		</form>
	</body>
</html>

 

六.常见问题

文件上传的时候会出现如下错误,这是被限制了上传文件的大小

org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: 
The field fileName exceeds its maximum permitted size of 1048576 bytes.

解决方案:

在配置文件里配置上传文件大小的最大值,单位必须是大写的 MB 或者 KB

spring:
  servlet:
    multipart:
      max-file-size: 50MB
      max-request-size: 50MB

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

study@lin017

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值