Spring Boot入门——文件上传与下载

原文来自:https://www.cnblogs.com/studyDetail/articles/7003253.html

1、在pom.xml文件中添加依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.wyl</groupId>

<artifactId>SpringBootFile</artifactId>

<version>0.0.1-SNAPSHOT</version>

<packaging>jar</packaging>

<name>SpringBootFile</name>

<url>http://maven.apache.org</url>

<properties>

<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

<java.version>1.7</java.version>

</properties>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>1.5.3.RELEASE</version>

</parent>

<dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>3.8.1</version>

<scope>test</scope>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<!-- thymeleaf模板插件 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

<!-- devtools插件,热部署 -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

<optional>true</optional>

<scope>true</scope>

</dependency>

</dependencies>

</project>

2、application.properties文件中取消模板文件缓存

spring.thymeleaf.cache=false

3、编写模板文件

file.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

<head>

<meta charset="UTF-8" />

<title>Insert title here</title>

</head>

<body>

<h1 th:inlines="text">文件上传</h1>

<form action="fileUpload" method="post" enctype="multipart/form-data">

<p>选择文件: <input type="file" name="fileName"/></p>

<p><input type="submit" value="提交"/></p>

</form>

</body>

</html>

multifile.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"

xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

<head>

<meta charset="UTF-8" />

<title>Insert title here</title>

</head>

<body>

<h1 th:inlines="text">文件上传</h1>

<form action="multifileUpload" method="post" enctype="multipart/form-data" >

<p>选择文件1: <input type="file" name="fileName"/></p>

<p>选择文件2: <input type="file" name="fileName"/></p>

<p>选择文件3: <input type="file" name="fileName"/></p>

<p><input type="submit" value="提交"/></p>

</form>

</body>

</html>

4、编写Controller

import org.springframework.stereotype.Controller;

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

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.multipart.MultipartFile;

@Controller

public class FileUploadController {

/*

* 获取file.html页面

*/

@RequestMapping("file")

public String file(){

return "/file";

}

/**

* 实现文件上传

* */

@RequestMapping("fileUpload")

@ResponseBody

public String fileUpload(@RequestParam("fileName") MultipartFile file){

if(file.isEmpty()){

return "false";

}

String fileName = file.getOriginalFilename();

int size = (int) file.getSize();

System.out.println(fileName + "-->" + size);

String path = "F:/test" ;

File dest = new File(path + "/" + fileName);

if(!dest.getParentFile().exists()){ //判断文件父目录是否存在

dest.getParentFile().mkdir();

}

try {

file.transferTo(dest); //保存文件

return "true";

} catch (IllegalStateException e) {

// TODO Auto-generated catch block

e.printStackTrace();

return "false";

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

return "false";

}

}

  /*

* 获取multifile.html页面

*/

@RequestMapping("multifile")

public String multifile(){

return "/multifile";

}

/**

* 实现多文件上传

* */

@RequestMapping(value="multifileUpload",method=RequestMethod.POST)

  /**public @ResponseBody String multifileUpload(@RequestParam("fileName")List<MultipartFile> files) */

public @ResponseBody String multifileUpload(HttpServletRequest request){

List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");

if(files.isEmpty()){

return "false";

}

String path = "F:/test" ;

for(MultipartFile file:files){

String fileName = file.getOriginalFilename();

int size = (int) file.getSize();

System.out.println(fileName + "-->" + size);

if(file.isEmpty()){

return "false";

}else{

File dest = new File(path + "/" + fileName);

if(!dest.getParentFile().exists()){ //判断文件父目录是否存在

dest.getParentFile().mkdir();

}

try {

file.transferTo(dest);

}catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

return "false";

}

}

}

return "true";

}

}

5、测试

 

  

6、多文件上传中遇到的问题

org.apache.tomcat.util.http.fileupload.FileUploadBase$FileSizeLimitExceededException: The field fileName exceeds its maximum permitted size of 1048576 bytes.

Spring Boot默认文件上传大小为2M,多文档上传中总是出现文件大小超出限度

解决方法:

a、在application.properties文件中设置文件大小

# Single file max size

multipart.maxFileSize=50Mb

# All files max size

multipart.maxRequestSize=50Mb

  但是,事实证明此种方法不能够解决以上问题

b、在启动类App.class文件中配置Bean来设置文件大小

import javax.servlet.MultipartConfigElement;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.web.servlet.MultipartConfigFactory;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

/**

* Hello world!

*

*/

@SpringBootApplication

@Configuration

public class App

{

public static void main( String[] args )

{

System.out.println( "Hello World!" );

SpringApplication.run(App.class, args);

}

/**

* 文件上传配置

* @return

*/

@Bean

public MultipartConfigElement multipartConfigElement() {

MultipartConfigFactory factory = new MultipartConfigFactory();

//单个文件最大

factory.setMaxFileSize("10240KB"); //KB,MB

/// 设置总上传数据总大小

factory.setMaxRequestSize("102400KB");

return factory.createMultipartConfig();

}

7、文件下载

@RequestMapping("download")

public String downLoad(HttpServletResponse response){

String filename="2.jpg";

String filePath = "F:/test" ;

File file = new File(filePath + "/" + filename);

if(file.exists()){ //判断文件父目录是否存在

response.setContentType("application/force-download");

response.setHeader("Content-Disposition", "attachment;fileName=" + filename);

byte[] buffer = new byte[1024];

FileInputStream fis = null; //文件输入流

BufferedInputStream bis = null;

OutputStream os = null; //输出流

try {

os = response.getOutputStream();

fis = new FileInputStream(file);

bis = new BufferedInputStream(fis);

int i = bis.read(buffer);

while(i != -1){

os.write(buffer);

i = bis.read(buffer);

}

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println("----------file download" + filename);

try {

bis.close();

fis.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

return null;

}

标签: Spring Boot

springboot文件上传下载,转载的的更多相关文章

  1. springboot文件上传下载简单使用

    springboot的文件上传比较简单 一.使用默认的Resolver:StandardServletMultipartResolver controller package com.mydemo.w ...

  2. SpringBoot文件上传下载

    项目中经常会有上传和下载的需求,这篇文章简述一下springboot项目中实现简单的上传和下载. 新建springboot项目,前台页面使用的thymeleaf模板,其余的没有特别的配置,pom代码如 ...

  3. springboot 文件上传下载

    关键点: 1,使用 POST 请求2,consumes=MediaType.MULTIPART_FROM_DATA_VALUE3,@RequestParm 里面的字符串和前端 input 控件的 na ...

  4. SpringBoot入门一:基础知识(环境搭建、注解说明、创建对象方法、注入方式、集成jsp/Thymeleaf、logback日志、全局热部署、文件上传/下载、拦截器、自动配置原理等)

    SpringBoot设计目的是用来简化Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置.通过这种方式,SpringBoot致力于在蓬勃发 ...

  5. 转载:JavaWeb 文件上传下载

    转自:https://www.cnblogs.com/aaron911/p/7797877.html 1. 文件上传下载概述 1.1. 什么是文件上传下载 所谓文件上传下载就是将本地文件上传到服务器端 ...

  6. SpringMVC——返回JSON数据&&文件上传下载

    --------------------------------------------返回JSON数据------------------------------------------------ ...

  7. SpringMVC文件上传下载

    在Spring MVC的基础框架搭建起来后,我们测试了spring mvc中的返回值类型,如果你还没有搭建好springmvc的架构请参考博文->http://www.cnblogs.com/q ...

  8. nodejs+express-实现文件上传下载管理的网站

    Nodejs+Express-实现文件上传下载管理的网站 项目Github地址(对你有帮助记得给星哟):https://github.com/qcer/updo 后端:基于nodejs的express ...

  9. 补习系列(11)-springboot 文件上传原理

    目录 一.文件上传原理 二.springboot 文件机制 临时文件 定制配置 三.示例代码 A. 单文件上传 B. 多文件上传 C. 文件上传异常 D. Bean 配置 四.文件下载 小结 一.文件 ...

随机推荐

  1. 性能问题: SQL*Net message from client 等待时间太长

    今天我终于自己遇到了这个问题, PO form 打不开了, 看了下 trace 发现 SQL*Net message from client 等待时间太长. 但是这不可能是网络问题, 这个环境是在我电 ...

  2. android基础知识复习——RelativeLayout布局属性、背景、半透明设置(XML设置)

    转自:http://blog.csdn.net/fansongy/article/details/6817968 复习布局与XML,写了一个空的登录界面.XML的注释我写在当行的后面了.程序运行图: ...

  3. Windows Server 2008 远程桌面连接拒绝

    (1)远程连接的时候在本地用户名添加域名 现象:在Windows2008R2配置成域控制器前,还没有安装AD,管理员Admistrator以及新创建的用户(创建的时候将该用户加入远程桌面管理组),发现 ...

  4. 轻松编写 C++ 单元测试

    单元测试概述 测试并不只是测试工程师的责任,对于开发工程师,为了保证发布给测试环节的代码具有足够好的质量( Quality ),为所编写的功能代码编写适量的单元测试是十分必要的. 单元测试( Unit ...

  5. 《深入理解Java虚拟机》笔记5

    Java虚拟机可以执行的语言并不是只有Java语言,比如jython也可以 运行在Java虚拟机上.不明白字节码之前觉得挺疑惑,为什么和Java 完全不同语法的程序语言也可以运行在虚拟机上呢? 不得不 ...

  6. You Gotta Care About the Code

    You Gotta Care About the Code Pete Goodliffe IT DOESN'T TAKE SHERLOCK HOLMES to work out that good p ...

  7. Silverlight 安装失败 提示 消息 ID 1603 的解决方法

    消息 ID: 1603 安装过程中出现错误.请执行以下步骤 原因是在以前安装过silverlight,没有安装成功或者没有彻底卸载干净,遗留了一些文件,尤其是安装时突然中断的时候会出现这个问题. 解决 ...

  8. redis学习笔记——RDB和AOF持久化二

    上一篇对RDB的源码分析是比较多的,但是AOF持久化执行进行了一些理论上的分析和概念的说明.本来想自己偷一些懒,将上篇文章中最后所给链接的AOF实现代码随便过一过算了,后来也就是在过的过程中发现自己这 ...

  9. centos 6.5 安装 cx_Oracle 5.12 步骤 ,使用oracle instantclient12.1

    新建sh文件 内容如下: 以su用户执行这个文件 #!/bin/bash # INSTALL ORACLE INSTANT CLIENT # ############################# ...

  10. strtok()切割字符串函数

    #include <iostream> #include <string.h> using namespace std; char *my_strtok(char *dist, ...