栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

SpringBoot文件上传下载

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot文件上传下载

项目中经常会有上传和下载的需求,这篇文章简述一下springboot项目中实现简单的上传和下载。

新建springboot项目,前台页面使用的thymeleaf模板,其余的没有特别的配置,pom代码如下:



    4.0.0

    com.dalaoyang
    springboot_upload_download
    0.0.1-SNAPSHOT
    jar

    springboot_upload_download
    springboot_upload_download

    
 org.springframework.boot
 spring-boot-starter-parent
 1.5.9.RELEASE
  
    

    
 UTF-8
 UTF-8
 1.8
    

    
 
     org.springframework.boot
     spring-boot-starter-thymeleaf
 
 
     org.springframework.boot
     spring-boot-starter-web
 

 
     org.springframework.boot
     spring-boot-devtools
     runtime
 
 
     org.springframework.boot
     spring-boot-starter-test
     test
 

 
     net.sourceforge.nekohtml
     nekohtml
     1.9.15
 
    

    
 
     
  org.springframework.boot
  spring-boot-maven-plugin
     
 
    

前台页面index.html,其中包含单个上传,下载,批量上传。




    
    Title


单文件上传


文件下载

下载文件

多文件上传

IndexController只是用来页面的跳转

package com.dalaoyang.Controller;

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


@Controller
public class IndexController {

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

最后是本文的重点,FileController,其中包含单个上传,单个下载,批量上传对应的方法。需要注意下载功能写的是对应我电脑里面固定位置的文件,仅供大家来参考。以下是代码:

package com.dalaoyang.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.util.List;


@RestController
public class FileController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @RequestMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
 try {
     if (file.isEmpty()) {
  return "文件为空";
     }
     // 获取文件名
     String fileName = file.getOriginalFilename();
     log.info("上传的文件名为:" + fileName);
     // 获取文件的后缀名
     String suffixName = fileName.substring(fileName.lastIndexOf("."));
     log.info("文件的后缀名为:" + suffixName);
     // 设置文件存储路径
     String 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 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 = "/Users/dalaoyang/Downloads/";
     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 "第 " + i + " 个文件上传失败 ==> "
+ e.getMessage();
  }
     } else {
  return "第 " + i
   + " 个文件上传失败因为文件为空";
     }
 }
 return "上传成功";
    }

    @GetMapping("/download")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
 String fileName = "dalaoyang.jpeg";// 文件名
 if (fileName != null) {
     //设置文件路径
     File file = new File("/Users/dalaoyang/documents/dalaoyang.jpeg");
     //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 "下载失败";
    }
}

源码下载 :大老杨码云

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/235251.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号