SpringBoot 文件上傳下載

前言

項目中經(jīng)常會有上傳和下載的需求,這篇文章簡述一下springboot項目中實現(xiàn)簡單的上傳和下載。前臺頁面使用的thymeleaf模板。

1、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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.huzh</groupId>
    <artifactId>springboot-upload-download</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>springboot-upload-download</name>
    <description>springboot-upload-download</description>

    <properties>
        <java.version>1.8</java.version>
        <nekohtml.version>1.9.22</nekohtml.version>
    </properties>

    <dependencies>
        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--HTML解析器和標記平衡器。-->
        <dependency>
            <groupId>net.sourceforge.nekohtml</groupId>
            <artifactId>nekohtml</artifactId>
            <version>${nekohtml.version}</version>
        </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>
    </dependencies>

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

2、創(chuàng)建index.html頁面

包含單個上傳,下載,批量上傳。

<!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 action="batch" method="POST" enctype="multipart/form-data">
    <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>

3、創(chuàng)建IndexController類

用于做頁面的跳轉

@Controller
public class IndexController {

    @RequestMapping("/")
    public String index() {
        return "index";
    }
}

4、創(chuàng)建FileController類

包含單個上傳,單個下載,批量上傳對應的方法。
MultipartFile 這個類一般是用來接受前臺傳過來的文件。

@RestController
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @RequestMapping(value = "upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "文件為空";
            }
            // 獲取文件名
            String fileName = file.getOriginalFilename();
            logger.info("上傳的文件名為:" + fileName);
            // 獲取文件的后綴名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            logger.info("文件的后綴名為:" + suffixName);
            //設置文件存儲路徑
            String filePath = "D:/huzh/workspace/springboot_workspace/file/";
            String path = filePath + fileName;
            File dest = new File(path);
            if (!dest.getParentFile().exists()) {
                //新建文件
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            return "上傳成功";
        } catch (Exception 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 = "D:/huzh/workspace/springboot_workspace/file/";
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            //設置文件路徑及名字
                            new File(filePath + file.getOriginalFilename())));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    return "第 " + i + " 個文件上傳失敗 ==> "
                            + e.getMessage();
                }
            } else {
                return "第 " + i
                        + " 個文件上傳失敗因為文件為空";
            }
        }
        return "上傳成功";
    }

    @GetMapping("/download")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
        String fileName = "123.jpg";
        if (fileName != null) {
            File file = new File("D:/huzh/workspace/springboot_workspace/file/1.jpg");
            if (file.exists()) {
                // 設置強制下載不打開
                response.setContentType("application/force-download");
                // 設置文件名
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                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 "下載失敗";
    }
}
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內(nèi)容

  • 項目中經(jīng)常會有上傳和下載的需求,這篇文章簡述一下springboot項目中實現(xiàn)簡單的上傳和下載。 新建spring...
    dalaoyang閱讀 58,880評論 7 88
  • 服務器中的文件上傳下載是基本操作,圖片、用戶頭像的上傳下載、文件的傳輸和資源分享等已經(jīng)成為每個應用必不可少的功能。...
    G63HH閱讀 366評論 0 0
  • 有啥不懂的或者出錯的可以在下面留言。 1. 文件上傳 返回是String就是文件所在路徑,一般把它放到數(shù)據(jù)庫中。我...
    FantJ閱讀 2,774評論 0 6
  • 做一個app更新的文件管理中心
    織夢少年666閱讀 2,718評論 0 2
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴謹 對...
    cosWriter閱讀 11,135評論 1 32