springBoot实现文件上传与下载

1. 文件下载

准备一个文件C:/Users/admin/Desktop/test.xlsx

 /**
     * 定制分析下载模板文档
     * @param response
     * @return
     */
    @RequestMapping("/downLoadTemplateExcel")
    public Info downLoadTemplateExcel(HttpServletResponse response){
        logger.info("/customAnalysisConfig/downLoadTemplateExcel");
        Info infos=new Info();
        // 创建输入输出流
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        //String url = "C:/Users/admin/Desktop/test.xlsx";
        String url =null;
        if(environment.equals("local")){//本地文件路径
            url ="C:/Users/admin/Desktop/test.xlsx";
        }else {//服务器文件路径
            url = "/usr/java/test.xlsx";
        }
        String downLoadPath = url;
        String fileName="template.xlsx";//生成的文件名
        File file2 = new File(downLoadPath);//要下载的文件对象
        if (!file2.exists()) {//如果目录不存在,创建目录
            file2.mkdirs();
        }
        long fileLength = file2.length();// 获取文件长度
        try {
            //Content-Disposition: attachment; filename="filename.xls"
            //第一个参数是attachment(意味着消息体应该被下载到本地;大多数浏览器会呈现一个“保存为”的对话框,
            // 将filename的值预填为下载后的文件名,假如它存在的话)
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            //Content-Type 实体头部用于指示资源的MIME类型 media type
            response.setHeader("Content-Type", "application/json");
            //Content-Length, HTTP消息长度, 用十进制数字表示的八位字节的数目
            response.setHeader("Content-Length", String.valueOf(fileLength));
            // 创建输入输出流实例
            bis = new BufferedInputStream(new FileInputStream(downLoadPath));
            bos = new BufferedOutputStream(response.getOutputStream());
            // 创建字节缓冲大小
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (bis != null)
                try {
                    bis.close();// 关闭输入流
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (bos != null)
                try {
                    bos.close();// 关闭输出流
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        infos.setCode("1");
        infos.setMsg("成功");
        return infos ;
    }

2. 单文件上传

准备一个upload.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="http://localhost:4000/pdClientManagerSystem/customAnalysisConfig/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" value="Select your file: ">
        <input type="submit" value="Upload">
    </form>
</body>
</html>

注意这里的 name="file"

//单文件上传的功能
    @RequestMapping(value = "/upload")
    public String upload(MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "file is empty";
            }
            String fileName = file.getOriginalFilename();//获取文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));//切割文件名
            log.info("上传的文件名为:" + fileName + " 后缀名为" + suffixName);
            // 设置文件存储路径(D盘),你可以存放在你想要指定的路径里面。
            String filePath = "D:/upload";
            //文件存放路径=filePath+/+ fileName
            String path = filePath + "/" + fileName;
            File dest = new File(path);
            // 检测是否存在目录
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夹
            }
            file.transferTo(dest);// 文件写入到上述的存放路径path
            return "upload success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "upload failure";
    }

3. 多文件上传

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>批量文件上传</title>
</head>
<body>
<form method="post" action="/batch" enctype="multipart/form-data">
<input type="file" name="file"><br> <input type="file" name="file"><br> <input type="file" name="file"><br> <br> <input type="submit" value="提交"> </form> </body> </html>

java代码

//多文件上传的功能
    @RequestMapping("/batch")
    public String handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            String filePath = "D:/uploads";
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(filePath  + "/" + file.getOriginalFilename())));
                    stream.write(bytes);// 写入
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    return "the " + i + " file upload failure";
                }
            } else {
                return "the " + i + " file is empty";
            }
        }
        return "upload Multifile success";
    }
/**
* 定制分析下载模板文档
* @param response
* @return
*/
@RequestMapping("/downLoadTemplateExcel")
public Info downLoadTemplateExcel(HttpServletResponse response){
logger.info("/customAnalysisConfig/downLoadTemplateExcel");
Info infos=new Info();
// 创建输入输出流
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
//String url = "C:/Users/admin/Desktop/test.xlsx";
String url =null;
if(environment.equals("local")){//本地文件路径
url ="C:/Users/admin/Desktop/test.xlsx";
}else {//服务器文件路径
url = "/usr/java/test.xlsx";
}
String downLoadPath = url;
String fileName="template.xlsx";//生成的文件名
File file2 = new File(downLoadPath);//要下载的文件对象
if (!file2.exists()) {//如果目录不存在,创建目录
file2.mkdirs();
}
long fileLength = file2.length();// 获取文件长度
try {
//Content-Disposition: attachment; filename="filename.xls"
//第一个参数是attachment(意味着消息体应该被下载到本地;大多数浏览器会呈现一个保存为的对话框,
// filename的值预填为下载后的文件名,假如它存在的话)
response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
//Content-Type 实体头部用于指示资源的MIME类型 media type
response.setHeader("Content-Type", "application/json");
//Content-Length, HTTP消息长度, 用十进制数字表示的八位字节的数目
response.setHeader("Content-Length", String.valueOf(fileLength));
// 创建输入输出流实例
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
// 创建字节缓冲大小
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (bis != null)
try {
bis.close();// 关闭输入流
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null)
try {
bos.close();// 关闭输出流
} catch (IOException e) {
e.printStackTrace();
}
}
infos.setCode("1");
infos.setMsg("成功");
return infos ;
}
原文地址:https://www.cnblogs.com/lusaisai/p/13329729.html