詳解SpringBoot文件上傳下載和多文件上傳(圖文)
最近在學(xué)習(xí)SpringBoot,以下是最近學(xué)習(xí)整理的實(shí)現(xiàn)文件上傳下載的Java代碼:
1、開(kāi)發(fā)環(huán)境:
IDEA15+ Maven+JDK1.8
2、新建一個(gè)maven工程:
3、工程框架
4、pom.xml文件依賴(lài)項(xiàng)
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SpringWebContent</groupId> <artifactId>SpringWebContent</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>SpringWebContent Maven Webapp</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.3.RELEASE</version> </parent> <dependencies> <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>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <properties> <java.version>1.8</java.version> </properties> <build> <finalName>SpringWebContent</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
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);
//文件上傳相關(guān)代碼
@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//";
// 解決中文問(wèn)題,liunx下中文路徑,圖片顯示問(wèn)題
// fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
// 檢測(cè)是否存在目錄
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
return "上傳成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上傳失敗";
}
//文件下載相關(guān)代碼
@RequestMapping("/download")
public String downloadFile(org.apache.catalina.servlet4preview.http.HttpServletRequest request, HttpServletResponse response){
String fileName = "FileUploadTests.java";
if (fileName != null) {
//當(dāng)前是從該工程的WEB-INF//File//下獲取文件(該目錄可以在下面一行代碼配置)然后下載到C:\\users\\downloads即本機(jī)的默認(rèn)下載的目錄
String realPath = request.getServletContext().getRealPath(
"http://WEB-INF//");
File file = new File(realPath, fileName);
if (file.exists()) {
response.setContentType("application/force-download");// 設(shè)置強(qiáng)制下載不打開(kāi)
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);
}
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<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
+ " because the file was empty.";
}
}
return "upload successful";
}
7、index.html
<!DOCTYPE html> <html lang="en"> <head> <title>Getting Started: Serving Web Content</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <p>Get your greeting <a href="/greeting" rel="external nofollow" >here</a></p> <form action="/upload" method="POST" enctype="multipart/form-data"> 文件:<input type="file" name="test"/> <input type="submit" /> </form> <a href="/download" rel="external nofollow" >下載test</a> <p>多文件上傳</p> <form method="POST" enctype="multipart/form-data" action="/batch/upload"> <p>文件1:<input type="file" name="file" /></p> <p>文件2:<input type="file" name="file" /></p> <p><input type="submit" value="上傳" /></p> </form> </html>
完整工程地址:SpringWebContent_jb51.rar
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java圖片讀取ImageIO.read()報(bào)錯(cuò)問(wèn)題及解決
在使用imageio庫(kù)讀取圖片時(shí),如果路徑中包含中文,可能會(huì)導(dǎo)致讀取失敗,解決方法是將路徑中的中文字符進(jìn)行轉(zhuǎn)義處理,可以使用ImageUtil.java工具類(lèi)進(jìn)行路徑轉(zhuǎn)義,從而避免錯(cuò)誤,這是一個(gè)常見(jiàn)問(wèn)題,希望本文的解決方案能幫助到遇到相同問(wèn)題的開(kāi)發(fā)者2024-10-10
IDEA新建bootstrap.yml文件不顯示葉子圖標(biāo)的問(wèn)題
這篇文章主要介紹了IDEA新建bootstrap.yml文件不顯示葉子圖標(biāo)的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
spring?MVC實(shí)現(xiàn)簡(jiǎn)單登錄功能
這篇文章主要為大家詳細(xì)介紹了spring?MVC實(shí)現(xiàn)簡(jiǎn)單登錄功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-09-09
BlockingQueue隊(duì)列處理高并發(fā)下的日志
這篇文章主要介紹了BlockingQueue隊(duì)列處理高并發(fā)下的日志示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03
Java畢業(yè)設(shè)計(jì)實(shí)戰(zhàn)之養(yǎng)老院管理系統(tǒng)的實(shí)現(xiàn)
讀萬(wàn)卷書(shū)不如行萬(wàn)里路,只學(xué)書(shū)上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+JSP+Easyui+maven+mysql實(shí)現(xiàn)一個(gè)養(yǎng)老院管理系統(tǒng),大家可以在過(guò)程中查缺補(bǔ)漏,提升水平2022-03-03
使用mybatis的typeHandler對(duì)clob進(jìn)行流讀寫(xiě)方式
這篇文章主要介紹了使用mybatis的typeHandler對(duì)clob進(jìn)行流讀寫(xiě)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01
詳解Mybatis 傳遞參數(shù)類(lèi)型為L(zhǎng)ist的取值問(wèn)題
這篇文章主要介紹了詳解Mybatis 傳遞參數(shù)類(lèi)型為L(zhǎng)ist的取值問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
Java springboot Mongodb增刪改查代碼實(shí)例
這篇文章主要介紹了Java springboot Mongodb增刪改查代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07

