spring boot 的上传和下载 (一)

我们现在进行的是springboot 的一个简单的上传和下载:

我们先编辑一个跳转的页面 skipController :

package com.haihua.haihua.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class skipController {

    @RequestMapping("/puTong")
    public String index()
    {
        return "puTong";
    }
}

下面是我们html 请求页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>spring boot普通的上传和下载</title>
</head>
<body>
<p>单文件上传</p>
<form action="upload" method="POST" enctype="multipart/form-data">
    文件:<input type="file" name="file"/>
    <input type="submit"/>
</form>
<hr/>
<p>文件下载</p>
<a href="download">下载文件</a>
<hr/>
<p>多文件上传</p>
<form method="POST" enctype="multipart/form-data" action="batch">
    <p>文件1:<input type="file" name="file"/></p>
    <p>文件2:<input type="file" name="file"/></p>
    <p><input type="submit" value="上传"/></p>
</form>
</body>
</html>

下面是我们的服务端:

package com.haihua.haihua.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
public class puTongController {

    private static final Logger log = LoggerFactory.getLogger(puTongController.class);

    @RequestMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            log.info("上传的文件名为:" + fileName);
            String str = (new SimpleDateFormat("yyyyMMddHHmmssSSS")).format(new Date());
            //加时间防止重复
            fileName= str +"-"+ fileName;
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            log.info("文件的后缀名为:" + suffixName);
            //系统名称
            String osName = System.getProperties().getProperty("os.name");
            log.info("系统名称:" + osName);
            // 设置文件存储路径
            String filePath = "";
            if (osName.contains("Windows")){
                filePath = "D:\\upload\\img\\";
            }else {
                filePath = "/Users/dalaoyang/Downloads/";
            }
            String path = filePath + fileName;
            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入
            return "上传成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    @PostMapping("/batch")
    public String handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        String osName = System.getProperties().getProperty("os.name");
        log.info("系统名称:" + osName);
        // 设置文件存储路径
        String filePath = "";
        if (osName.contains("Windows")){
            filePath = "D:\\upload\\img\\";
        }else {
            filePath = "/Users/dalaoyang/Downloads/";
        }
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);

            if (!file.isEmpty()) {
                try {
                    String fileName =(new SimpleDateFormat("yyyyMMddHHmmssSSS")).format(new Date()) + file.getOriginalFilename();
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(filePath + fileName)));//设置文件路径及名字
                    stream.write(bytes);// 写入
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    return "第 " + i + " 个文件上传失败 ==> "
                            + e.getMessage();
                }
            } else {
                return "第 " + i
                        + " 个文件上传失败因为文件为空";
            }
        }
        return "上传成功";
    }

    @GetMapping("/download")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        String osName = System.getProperties().getProperty("os.name");
        log.info("系统名称:" + osName);
        // 设置文件存储路径
        String filePath = "";
        if (osName.contains("Windows")){
            filePath = "D:\\upload\\img\\";
        }else {
            filePath = "/Users/dalaoyang/Downloads/";
        }
        String fileName = "20190426173325466-noavatar_middle.gif";// 文件名
        String pathname = filePath + fileName;
        if (fileName != null) {
            //设置文件路径
            File file = new File(pathname);
            //File file = new File(realPath , fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }
}

其中我们特别注意的两点:

  • 文件名的重复问题
  • window 本地和 Linux 服务器 不同的路径问题

1.文件名重复问题,我们获取他的旧名,又加上系统时间整形组合成新的文件名称,这样就不会重复了:

            // 获取文件名
            String fileName = file.getOriginalFilename();
            log.info("上传的文件名为:" + fileName);
            String str = (new SimpleDateFormat("yyyyMMddHHmmssSSS")).format(new Date());
            //加时间防止重复
            fileName= str +"-"+ fileName;

2.window 本地和 Linux 服务器 不同的路径问题,我们可以获取系统的名称,根据不同的系统配置不同的路径

            //系统名称
            String osName = System.getProperties().getProperty("os.name");
            log.info("系统名称:" + osName);
            // 设置文件存储路径
            String filePath = "";
            if (osName.contains("Windows")){
                filePath = "D:\\upload\\img\\";
            }else {
                filePath = "/Users/dalaoyang/Downloads/";
            }

猜你喜欢

转载自blog.csdn.net/weixin_40927959/article/details/89568589