項(xiàng)目中經(jīng)常會(huì)有上傳和下載的需求凶朗,這篇文章簡(jiǎn)述一下springboot項(xiàng)目中實(shí)現(xiàn)簡(jiǎn)單的上傳和下載值依。
新建springboot項(xiàng)目,前臺(tái)頁(yè)面使用的thymeleaf模板核无,其余的沒有特別的配置辖所,pom代碼如下:
<?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.dalaoyang</groupId>
<artifactId>springboot_upload_download</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot_upload_download</name>
<description>springboot_upload_download</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.15</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
前臺(tái)頁(yè)面index.html阀湿,其中包含單個(gè)上傳伤塌,下載缴允,批量上傳最疆。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>單文件上傳</p>
<form action="upload" method="POST" enctype="multipart/form-data">
文件:<input type="file" name="file"/>
<input type="submit"/>
</form>
<hr/>
<p>文件下載</p>
<a href="download">下載文件</a>
<hr/>
<p>多文件上傳</p>
<form method="POST" enctype="multipart/form-data" action="batch">
<p>文件1:<input type="file" name="file"/></p>
<p>文件2:<input type="file" name="file"/></p>
<p><input type="submit" value="上傳"/></p>
</form>
</body>
</html>
IndexController只是用來頁(yè)面的跳轉(zhuǎn)
package com.dalaoyang.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.Controller
* @email yangyang@dalaoyang.cn
* @date 2018/4/9
*/
@Controller
public class IndexController {
@RequestMapping("/")
public String index()
{
return "index";
}
}
最后是本文的重點(diǎn)杯巨,F(xiàn)ileController,其中包含單個(gè)上傳努酸,單個(gè)下載服爷,批量上傳對(duì)應(yīng)的方法。需要注意下載功能寫的是對(duì)應(yīng)我電腦里面固定位置的文件获诈,僅供大家來參考仍源。以下是代碼:
package com.dalaoyang.Controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
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;
/**
* @author dalaoyang
* @Description
* @project springboot_learn
* @package com.dalaoyang.Controller
* @email yangyang@dalaoyang.cn
* @date 2018/4/9
*/
@RestController
public class FileController {
private static final Logger log = LoggerFactory.getLogger(FileController.class);
@RequestMapping(value = "/upload")
public String upload(@RequestParam("file") MultipartFile file) {
try {
if (file.isEmpty()) {
return "文件為空";
}
// 獲取文件名
String fileName = file.getOriginalFilename();
log.info("上傳的文件名為:" + fileName);
// 獲取文件的后綴名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
log.info("文件的后綴名為:" + suffixName);
// 設(shè)置文件存儲(chǔ)路徑
String filePath = "/Users/dalaoyang/Downloads/";
String path = filePath + fileName;
File dest = new File(path);
// 檢測(cè)是否存在目錄
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();// 新建文件夾
}
file.transferTo(dest);// 文件寫入
return "上傳成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上傳失敗";
}
@PostMapping("/batch")
public 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);
String filePath = "/Users/dalaoyang/Downloads/";
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
stream = new BufferedOutputStream(new FileOutputStream(
new File(filePath + file.getOriginalFilename())));//設(shè)置文件路徑及名字
stream.write(bytes);// 寫入
stream.close();
} catch (Exception e) {
stream = null;
return "第 " + i + " 個(gè)文件上傳失敗 ==> "
+ e.getMessage();
}
} else {
return "第 " + i
+ " 個(gè)文件上傳失敗因?yàn)槲募榭?;
}
}
return "上傳成功";
}
@GetMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "dalaoyang.jpeg";// 文件名
if (fileName != null) {
//設(shè)置文件路徑
File file = new File("/Users/dalaoyang/Documents/dalaoyang.jpeg");
//File file = new File(realPath , fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 設(shè)置強(qiáng)制下載不打開
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 設(shè)置文件名
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);
}
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 "下載失敗";
}
}
源碼下載 :大老楊碼云