Spring boot 实现单个或批量文件上传功能

 更新时间:2018年08月17日 13:48:11   作者:佳佳乐2503  
这篇文章主要介绍了Spring boot 实现单个或批量文件上传功能,非常不错,具有一定的参考借鉴价值,需要的朋友参考下吧

一:添加依赖:

<!-- thymeleaf模板插件 -->
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
   <!-- jsp依赖 -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
</dependency>
<dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-jasper</artifactId>
  <!--<scope>provided</scope>-->
</dependency>

二:application.xml配置文件路径:

#配置上传文件地址
image.location.path=f:/image/
#配置文件大小限制
spring.http.multipart.maxFileSize=100Mb
spring.http.multipart.maxRequestSize=100Mb
#静态页面的访问配置
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.mode=HTML5

三:编写静态页面(src/main/resources下建文件夹static(static存放静态文件,比如 css、js、image…)和templates(存放静态页面)两个是同级目录),先在templates 中新建一个 uploadimg.html。

<!DOCTYPE html>
<html>
 <head>
  <title>uploadimg.html</title>
  <meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
  <meta name="description" content="this is my page"></meta>
  <meta name="content-type" content="text/html; charset=UTF-8"></meta>
  <!--<link rel="stylesheet" type="text/css" href="./styles.css" rel="external nofollow" >-->
 </head>
 <body>
 <form enctype="multipart/form-data" method="post" action="/dc/fileUpload">
  图片<input type="file" name="file"/>
  <input type="submit" value="上传"/>
  </form>
 </body>
</html>

四:编写Controller层:

package com.hot.analysis.controller.file;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.hot.analysis.exception.MyException;
@RestController
public class FileUploadController {
 //获取配置文件的路径
 @Value("${image.location.path}")
 private String resourceDir;
 /**
   * 实现文件上传
   * */
 @RequestMapping(value = "/index")
 public ModelAndView toIndex() {
 ModelAndView mv = new ModelAndView("uploadimg");
 return mv;
 }
  //单个文件上传
  @RequestMapping("/dc/fileUpload")
  @ResponseBody 
  public String fileUpload( MultipartFile file){
   // 获取上传文件路径
    String uploadPath = file.getOriginalFilename();
    // 获取上传文件的后缀
    String fileSuffix = uploadPath.substring(uploadPath.lastIndexOf(".") + 1, uploadPath.length());
    if (fileSuffix.equals("apk")) {
    uploadPath = resourceDir;
    } else {
    // 上传目录地址
    // String uploadpath="E:/hot-manage/image/";//windows路径
    uploadPath =resourceDir;// liux路劲
    }
    // 上传文件名
    String fileName = new Date().getTime() + new Random().nextInt(100) + "." + fileSuffix;
    File savefile = new File(uploadPath + fileName);
    if (!savefile.getParentFile().exists()) {
    savefile.getParentFile().mkdirs();
    }
    try {
    file.transferTo(savefile);
    } catch (IllegalStateException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    if (fileSuffix.equals("apk")) {
    return "/apk/" + fileName;
    } else {
    return "/image/" + fileName;
    }
   }
 // 批量上传
  @PostMapping("/dc/moreFileUpload")
 public String bacthFileUpload(MultipartFile[] file) throws MyException {
  StringBuffer buffer = new StringBuffer();
  for (MultipartFile multipartFile : file) {
  String str = fileUpload(multipartFile);
  buffer.append(str);
  buffer.append(",");
  }
  String all = buffer.substring(0, buffer.length() - 1);
  return all;
 }
 // 删除文件
  @PostMapping("/dc/deleteFile")
  public String delFile(String path) {
   String resultInfo = null;
 int lastIndexOf = path.lastIndexOf("/");
 String sb = path.substring(lastIndexOf + 1, path.length());
 sb = "f:/image/" + sb;
 File file = new File(sb);
 if (file.exists()) {
  if (file.delete()) {
  resultInfo = "1-删除成功";
  } else {
  resultInfo = "0-删除失败";
  }
 } else {
  resultInfo = "文件不存在!";
 }
 return resultInfo;
 }
 //文件下载相关代码
  @RequestMapping("/download")
  public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
    String fileName = "aim_test.txt";// 设置文件名,根据业务需要替换成要下载的文件名
    if (fileName != null) {
      //设置文件路径
      String realPath = "D://aim//";
      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);
          }
          System.out.println("success");
        } 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 null;
  }

  }

测试:

成功返回路径:

查看文件夹:

总结

以上所述是小编给大家介绍的Spring boot 实现单个或批量文件上传功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

相关文章

  • Java Collections工具类中常用算法解析

    Java Collections工具类中常用算法解析

    在软件开发中,算法是非常重要的一部分,它们可以提供高效的数据处理和操作,这篇文章主要为大家介绍了Collections 工具类集合框架中常用算法,感兴趣的可以了解一下
    2023-06-06
  • Spring Security CsrfFilter过滤器用法实例

    Spring Security CsrfFilter过滤器用法实例

    这篇文章主要介绍了Spring Security CsrfFilter过滤器用法实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • Java 深入浅出讲解泛型与包装类

    Java 深入浅出讲解泛型与包装类

    泛型是在Java SE 1.5引入的的新特性,本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。这种参数类型可以用在类、接口和方法的创建中,分别称为泛型类、泛型接口、泛型方法,本篇我们一起来学习泛型以及包装类
    2022-04-04
  • mybatis-plus getOne和逻辑删除问题详解

    mybatis-plus getOne和逻辑删除问题详解

    这篇文章主要介绍了mybatis-plus getOne和逻辑删除,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-08-08
  • 学习Java多线程之线程定义、状态和属性

    学习Java多线程之线程定义、状态和属性

    这篇文章主要为大家详细介绍了Java多线程之线程定义、状态和属性,感兴趣的小伙伴们可以参考一下
    2016-02-02
  • 如何使用Jenkins构建GIT+Maven项目

    如何使用Jenkins构建GIT+Maven项目

    这篇文章主要介绍了如何使用Jenkins构建GIT+Maven项目,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-09-09
  • Java语言实现基数排序代码分享

    Java语言实现基数排序代码分享

    这篇文章主要介绍了Java语言实现基数排序代码分享,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • Spring Gateway基本使用示例小结

    Spring Gateway基本使用示例小结

    Springcloud Gateway使用了Webflux中的reactor-netty响应式编程组件,底层使用了Netty通讯框架,具体一些特征,本文结合实例代码对Spring Gateway使用给大家介绍的非常详细,感兴趣的朋友一起看看吧
    2023-11-11
  • List集合多个复杂字段判断去重的案例

    List集合多个复杂字段判断去重的案例

    今天小编就为大家分享一篇关于List集合多个复杂字段判断去重的案例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-12-12
  • 简单了解java volatile关键字实现的原理

    简单了解java volatile关键字实现的原理

    这篇文章主要介绍了简单了解volatile关键字实现的原理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08

最新评论