(1)新建maven Java project

新建一个名称为spring-boot-fileuploadmaven java项目

(2)在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>me.shijunjie</groupId>
<artifactId>spring-boot-fileuploadmaven</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>spring-boot-fileuploadmaven</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.4.RELEASE</version>
</parent> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- thmleaf模板依赖. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin </artifactId>
</plugin> <!-- <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin
</artifactId> <dependencies> springloaded hotdeploy <dependency> <groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId> <version>1.2.4.RELEASE</version> </dependency>
</dependencies> <executions> <execution> <goals> <goal>repackage</goal> </goals>
<configuration> <classifier>exec</classifier> </configuration> </execution>
</executions> </plugin> --> <!-- java编译插件 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>

(3)新建一个表单页面(这里使用thymeleaf)

在src/main/resouces新建templates(如果看过博主之前的文章,应该知道,templates是spring boot存放模板文件的路径),在templates下新建一个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>
<title>Hello World!</title>
</head>
<body>
<form method="POST" enctype="multipart/form-data" action="/upload">
<p>
文件:<input type="file" name="file" />
</p>
<p>
<input type="submit" value="上传" />
</p>
</form>
</body>
</html>

(4)编写controller;

package me.shijunjie.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest; @Controller
public class FileUploadController {
//访问路径为:http://127.0.0.1:8080/file
@RequestMapping("/file")
public String file(){
return "/file";
} @RequestMapping("/mutifile")
public String mutifile(){
return "/mutifile";
} @RequestMapping("/upload")
@ResponseBody
public String handleFileUpload(@RequestParam("file")MultipartFile file){
if(!file.isEmpty()){
try {
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
out.write(file.getBytes());
out.flush();
out.close();
}catch(FileNotFoundException e) {
e.printStackTrace();
return "上传失败,"+e.getMessage();
}catch (IOException e) {
e.printStackTrace();
return "上传失败,"+e.getMessage();
} return "上传成功"; }else{ return "上传失败,因为文件是空的."; }
} /** * 多文件具体上传时间,主要是使用了MultipartHttpServletRequest和MultipartFile * @param request * @return */ @RequestMapping(value="/batch/upload", method=RequestMethod.POST)
public @ResponseBody
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);
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
stream =
new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
stream.write(bytes);
stream.close();
} catch (Exception e) {
stream = null;
return "You failed to upload " + i + " =>" + e.getMessage();
}
} else {
return "You failed to upload " + i + " becausethe file was empty.";
}
}
return "upload successful"; }
}

(6)对上传的文件做一些限制;

package me.shijunjie.spring_boot_fileuploadmaven;

import javax.servlet.MultipartConfigElement;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan; @SpringBootApplication
@ComponentScan(value="me.shijunjie")
public class App
{
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
//// 设置文件大小限制 ,超了,页面会抛出异常信息,这时候就需要进行异常信息的处理了;
factory.setMaxFileSize("128KB"); //KB,MB
/// 设置总上传数据总大小
factory.setMaxRequestSize("256KB");
//Sets the directory location wherefiles will be stored.
//factory.setLocation("路径地址");
return factory.createMultipartConfig();
} public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}

多文件上传差不多,可以参照http://blog.csdn.net/linxingliang/article/details/52077816

最新文章

  1. bzoj1854--并查集
  2. AngularJS在IE8的支持
  3. python 实现登陆接口
  4. 通过yeelink平台监控树莓派CPU温度变化
  5. 专题——web.xml 中 url-pattern
  6. IntelliJ和tomcat中的目录结构
  7. C++ 面向对象的三个特点--多态性(二)
  8. 如何通过类找到对应的jar包
  9. EntityFramework查询oracle数据库时报ora-12704: character set mismatch
  10. C语言中最常用的三种输入输出函数scanf()、printf()、getchar()和putchar()
  11. mysql 使用说明-2
  12. extjs实现多国语音切换
  13. 为Fitnesse-20140630定制RestFixture代码
  14. Java 三大主流框架概述
  15. 转:JMeter基础--逻辑控制器Logic Controller
  16. 关于Maven中打包命令(项目中打补丁的时候用到)
  17. 分布式锁(一) Zookeeper分布式锁
  18. 第二章&#160;向量(a)接口与实现
  19. WAVE文件格式解析
  20. 解决UITableView在iOS7中UINavigationController里的顶部留白问题

热门文章

  1. js获取IE版本,while代码很特别
  2. combobox添加复选框
  3. [BJOI2017]树的难题 点分治,线段树合并
  4. 【JUC源码解析】PriorityBlockingQueue
  5. Linux的常用命令笔记
  6. php文章tag标签的增删
  7. Unity面试问题归总
  8. boot,rebuild,resize,migrate有关的scheduler流程
  9. 市场营销的4c原则
  10. 关于 WebView 知识点的详解