您的位置:首页 > 编程语言 > Java开发

spring boot 实现文件上传和下载,以及多文件上传

2018-02-23 16:27 1056 查看
(1)、创建maven项目

(2)、在templates中创建html文件

<!DOCTYPE html>
<html lang="en">
<head>
<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>
<title>fileUpload</title>
</head>
<body>

<form action="/upload" enctype="multipart/form-data" method="post">
姓名:<input type="text" name="username"/>
<br/>
头像:<input type="file" name="filename"/>
<input type="submit" value="上传"/>
</form>
<hr/>
<a href="/download">文件下载</a>
<br/>
<form action="/batch/upload" method="post" enctype="multipart/form-data">
文件1:<input type="file" name="file"/><br/>
文件2:<input type="file" name="file"/><br/>
<input type="submit" value="多文件上传"/>
</form>

</body>
</html>


(3)、在webapp下创建存储临时文件夹file

(4)、pom.xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<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.example.file</groupId>
<artifactId>fileupload</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>fileupload</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>org.apache.
14252
maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</dependency>

<!--处理日志-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
</dependency>

<!--thymeleaf,自动跳转-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>

<!--连接数据库-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!--整合 mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.26</version>
</dependency>

<!--支持jsp-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


(5)、controller代码:

package com.example.file.fileupload.controller;

import com.example.file.fileupload.entity.Users;
import com.example.file.fileupload.service.UsersService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Controller
public class FileController {
//导入service层
@Resource
private UsersService usersService;

@RequestMapping(value = "/goto",method = RequestMethod.GET)
public String goUpload(){
return "index";
}
//日志信息
private static final Logger logger = LoggerFactory.getLogger(FileController.class);
//文件上传相关代码
@RequestMapping(value = "/upload",method = RequestMethod.POST)
@ResponseBody
public String upload(@RequestParam("filename") MultipartFile file,@RequestParam("username") String username,
HttpServletRequest request){
//判断文件是否为空
if(file.isEmpty()){
return "文件为空";
}
//获取文件名
String fileName = file.getOriginalFilename();
logger.info("上传文件名为:"+fileName);
//获取文件后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
logger.info("文件的后缀名为:"+suffixName);
//上传后存放路径,webapp/file
String filePath = request.getSession().getServletContext().getRealPath("file/");
//重命名文件名
String fileNewName = System.currentTimeMillis()+suffixName;
//创建文件目录
File src = new File(filePath+fileNewName);
//检查文件目录是否存在
if(!src.getParentFile().exists()){
src.getParentFile().mkdirs();
}
//上传文件
try{
file.transferTo(src);
//上传文件保存到数据库
Users u = new Users();
logger.info("username="+username);
u.setUserName(username);
u.setPhoto("file/"+fileNewName);
this.usersService.insertUsers(u);
return "上传成功!";
}catch (Exception e){
e.printStackTrace();
}
return "上传失败!";
}

//文件下载代码
@RequestMapping(value = "/download",method = RequestMethod.GET)
public String downFile(HttpServletRequest request, HttpServletResponse response){
String fileName = "123.jpg";
if(fileName != null){
//获取当前路径下的文件
String realPath = request.getServletContext().getRealPath("/file/")+fileName;
File file = new File(realPath);
//判断文件的对否存在
if(file.exists()){
//设置强制下载,不打开
response.setContentType("application/x-msdownload");
//设置文件名
response.addHeader("Content-Disposition","attachment;fileName="+fileName);
byte[]  bytes = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;

try{
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int b = bis.read(bytes);
while(b != -1){
os.write(bytes,0,b);
b = bis.read(bytes);
}
os.close();
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 "下载失败!";
}

//多文件上传
@RequestMapping(value = "/batch/upload",method = RequestMethod.POST)
@ResponseBody
public String MoreFileUpload(HttpServletRequest request){
//获取上传文件list
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
MultipartFile file = null;
BufferedOutputStream bos = null;
//遍历文件
for(int i = 0; i < files.size();i++){
file = files.get(i);
//判断文件的是否存在
if(!file.isEmpty()){
try{
//获取文件名
String fileName = file.getOriginalFilename();
logger.info("上传文件名为:"+fileName);
//获取文件后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
logger.info("文件的后缀名为:"+suffixName);
//上传后存放路径,webapp/file
String filePath = request.getSession().getServletContext().getRealPath("file/");
//重命名文件名
String fileNewName = System.currentTimeMillis()+suffixName;
//System.out.println("当前文件名:"+fileName);
//创建文件目录
File src = new File(filePath+fileNewName);
//检查文件目录是否存在
byte[] bytes = file.getBytes();
bos = new BufferedOutputStream(new FileOutputStream(src));
bos.write(bytes);
bos.close();
}catch (Exception e){
bos = null;
return "上传失败原因是:"+e.getMessage();
}
}
return "上传失败!";
}
return "上传成功!";
}
}


(6)、运行http://localhost:8080/**即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: