详解SpringBoot文件上传下载和多文件上传图文

本篇文章主要介绍了详解SpringBoot文件上传下载和多文件上传(图文),具有一定的参考价值,感兴趣的小伙伴们可以参考一下。

最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的Java代码

1、开发环境:

IDEA15+ Maven+JDK1.8

2、新建一个maven工程:

 

3、工程框架

 

4、pom.xml文件依赖项

4.0.0SpringWebContentSpringWebContentwar1.0-SNAPSHOTSpringWebContent Maven Webapphttp://maven.apache.orgorg.springframework.bootspring-boot-starter-parent1.4.3.RELEASEOrg.springframework.bootspring-boot-starter-thymeleaforg.springframework.bootspring-boot-devtoolstruejunitjunit3.8.1test1.8SpringWebContentorg.springframework.bootspring-boot-maven-plugin

5、Application.java

import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }

6、FileController.java

import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ResponseBody; 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; @Controller public class FileController { @RequestMapping("/greeting") public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) { model.addAttribute("name", name); return "greeting"; } private static final Logger logger = LoggerFactory.getLogger(FileController.class); //文件上传相关代码 @RequestMapping(value = "upload") @ResponseBody public String upload(@RequestParam("test") multipartfile file) { if (file.isEmpty()) { return "文件为空"; } // 获取文件名 String fileName = file.getoriginalFilename(); logger.info("上传文件名为:" + fileName); // 获取文件的后缀名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); logger.info("上传的后缀名为:" + suffixName); // 文件上传后的路径 String filePath = "E://test//"; // 解决中文问题,liunx下中文路径,图片显示问题 // fileName = UUID.randomUUID() + suffixName; File dest = new File(filePath + fileName); // 检测是否存在目录 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); return "上传成功"; } catch (IllegalStateException e) { e.printstacktrace(); } catch (IOException e) { e.printstacktrace(); } return "上传失败"; } //文件下载相关代码 @RequestMapping("/download") public String downloadFile(org.apache.catalina.servlet4preview.http.HttpServletRequest request, HttpServletResponse response){ String fileName = "FileUploadTests.java"; if (fileName != null) { //当前是从该工程的WEB-INF//File//下获取文件(该目录可以在下面一行代码配置)然后下载到C:\users\downloads即本机的认下载的目录 String realPath = request.getServletContext().getRealPath( "//WEB-INF//"); 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; } //多文件上传 @RequestMapping(value = "/batch/upload", method = RequestMethod.POST) @ResponseBody public String handleFileUpload(HttpServletRequest request) { List files = ((MultipartHttpServletRequest) request) .getFiles("file"); multipartfile file = null; bufferedoutputstream stream = null; for (int i = 0; i " + e.getMessage(); } } else { return "You Failed to upload " + i + " because the file was empty."; } } return "upload successful"; }

7、index.html

Getting Started: Serving Web ContentGet your greeting here

文件

下载test多文件上传

文件1:

文件2:

完整工程地址:SpringWebContent_jb51.rar

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

相关文章

HashMap是Java中最常用的集合类框架,也是Java语言中非常典型...
在EffectiveJava中的第 36条中建议 用 EnumSet 替代位字段,...
介绍 注解是JDK1.5版本开始引入的一个特性,用于对代码进行说...
介绍 LinkedList同时实现了List接口和Deque接口,也就是说它...
介绍 TreeSet和TreeMap在Java里有着相同的实现,前者仅仅是对...
HashMap为什么线程不安全 put的不安全 由于多线程对HashMap进...