SpringBoot文件上傳下載

項(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 "下載失敗";
    }
}

源碼下載 :大老楊碼云

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市舔涎,隨后出現(xiàn)的幾起案子笼踩,更是在濱河造成了極大的恐慌,老刑警劉巖亡嫌,帶你破解...
    沈念sama閱讀 222,183評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件嚎于,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡挟冠,警方通過查閱死者的電腦和手機(jī)于购,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來知染,“玉大人肋僧,你說我怎么就攤上這事。” “怎么了嫌吠?”我有些...
    開封第一講書人閱讀 168,766評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵伪窖,是天一觀的道長(zhǎng)。 經(jīng)常有香客問我居兆,道長(zhǎng)覆山,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,854評(píng)論 1 299
  • 正文 為了忘掉前任泥栖,我火速辦了婚禮簇宽,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘吧享。我一直安慰自己魏割,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,871評(píng)論 6 398
  • 文/花漫 我一把揭開白布钢颂。 她就那樣靜靜地躺著钞它,像睡著了一般。 火紅的嫁衣襯著肌膚如雪殊鞭。 梳的紋絲不亂的頭發(fā)上遭垛,一...
    開封第一講書人閱讀 52,457評(píng)論 1 311
  • 那天,我揣著相機(jī)與錄音操灿,去河邊找鬼锯仪。 笑死,一個(gè)胖子當(dāng)著我的面吹牛趾盐,可吹牛的內(nèi)容都是我干的庶喜。 我是一名探鬼主播,決...
    沈念sama閱讀 40,999評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼救鲤,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼久窟!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起本缠,我...
    開封第一講書人閱讀 39,914評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤斥扛,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后搓茬,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體犹赖,經(jīng)...
    沈念sama閱讀 46,465評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,543評(píng)論 3 342
  • 正文 我和宋清朗相戀三年卷仑,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片麸折。...
    茶點(diǎn)故事閱讀 40,675評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡锡凝,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出垢啼,到底是詐尸還是另有隱情窜锯,我是刑警寧澤张肾,帶...
    沈念sama閱讀 36,354評(píng)論 5 351
  • 正文 年R本政府宣布,位于F島的核電站锚扎,受9級(jí)特大地震影響吞瞪,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜驾孔,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,029評(píng)論 3 335
  • 文/蒙蒙 一芍秆、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧翠勉,春花似錦妖啥、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至朽们,卻和暖如春怀读,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背骑脱。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評(píng)論 1 274
  • 我被黑心中介騙來泰國(guó)打工愿吹, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人惜姐。 一個(gè)月前我還...
    沈念sama閱讀 49,091評(píng)論 3 378
  • 正文 我出身青樓犁跪,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親歹袁。 傳聞我的和親對(duì)象是個(gè)殘疾皇子坷衍,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,685評(píng)論 2 360

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

  • 有啥不懂的或者出錯(cuò)的可以在下面留言。 1. 文件上傳 返回是String就是文件所在路徑条舔,一般把它放到數(shù)據(jù)庫(kù)中枫耳。我...
    FantJ閱讀 2,772評(píng)論 0 6
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,307評(píng)論 25 707
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,859評(píng)論 6 342
  • #三月春日游# 梅州豐順縣。八鄉(xiāng)山大峽谷孟抗。相比全國(guó)其他地方的大峽谷迁杨,這里從谷口到谷尾,綿延6.5公里凄硼,峽谷四周都是...
    勒克兒閱讀 1,317評(píng)論 1 2