Springboot 文件上傳下載

做一個(gè)app更新的文件管理中心

<?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>2.0.4.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.projectlombok</groupId>
            <artifactId>lombok</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>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
package com.source.controller;

import com.source.entity.ApkUpdate;
import com.source.service.ApkUpdateService;
import com.source.utils.DateUtil;
import com.source.utils.SysConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
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.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


/**
 * @author source
 * @Description
 * @project springboot_learn
 * @package com.source.controller
 * @email yangyang@source.cn
 * @date 2018/4/9
 */
@Slf4j
@RestController
public class FileController {

    @Autowired
    private ApkUpdateService apkUpdateService;

    @RequestMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        try {
            if (file.isEmpty()) {
                return "文件為空";
            }
            // 獲取文件名
            String fileName = file.getOriginalFilename();
            fileName = String.valueOf(System.currentTimeMillis())+fileName.substring(fileName.lastIndexOf("."),fileName.length());
            log.info("上傳的文件名為:" + fileName);
            //設(shè)置文件存儲(chǔ)路徑
            String filePath = SysConfig.UPLOADPATH;
            String path = filePath + fileName;
            String ServerUrl = request.getServerName()+":"+request.getServerPort()+"/download?fileName=";
            File dest = new File(path);
            // 檢測(cè)是否存在目錄
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();// 新建文件夾
            }
            file.transferTo(dest);// 文件寫入
            Map parameterMap = getParameterMap(request);
            ApkUpdate apkUpdate = new ApkUpdate();
            apkUpdate.setProjectId(Integer.parseInt(parameterMap.get("projectId").toString()));
            apkUpdate.setVersionCode(Integer.parseInt(parameterMap.get("versionCode").toString()));
            apkUpdate.setVersionName(parameterMap.get("versionName").toString());
            apkUpdate.setRemark(parameterMap.get("versionName").toString());
            apkUpdate.setAddress(ServerUrl+fileName);
            apkUpdate.setStates(1);
            apkUpdate.setCounts(0);
            apkUpdate.setReleaseTime(DateUtil.getDateTime());
            apkUpdateService.insertApkUpdate(apkUpdate);
            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 = SysConfig.UPLOADPATH;
            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 = request.getParameter("fileName");// 文件名
        if (fileName != null) {
            //設(shè)置文件路徑
            File file = new File(SysConfig.UPLOADPATH+fileName);
            //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 "下載失敗";
    }
   /**
     * 從request中獲得參數(shù)Map昙啄,并返回可讀的Map
     *
     * @param request
     * @return
     */
    public static Map getParameterMap(HttpServletRequest request) {
        // 參數(shù)Map
        Map properties = request.getParameterMap();
        // 返回值Map
        Map returnMap = new HashMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if(null == valueObj){
                value = "";
            }else if(valueObj instanceof String[]){
                String[] values = (String[])valueObj;
                for(int i=0;i<values.length;i++){
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length()-1);
            }else{
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末勿她,一起剝皮案震驚了整個(gè)濱河市塔沃,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌轻绞,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,826評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件佣耐,死亡現(xiàn)場(chǎng)離奇詭異政勃,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)兼砖,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門奸远,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人讽挟,你說我怎么就攤上這事懒叛。” “怎么了耽梅?”我有些...
    開封第一講書人閱讀 164,234評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵薛窥,是天一觀的道長。 經(jīng)常有香客問我眼姐,道長诅迷,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,562評(píng)論 1 293
  • 正文 為了忘掉前任妥凳,我火速辦了婚禮竟贯,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘逝钥。我一直安慰自己屑那,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評(píng)論 6 392
  • 文/花漫 我一把揭開白布艘款。 她就那樣靜靜地躺著持际,像睡著了一般。 火紅的嫁衣襯著肌膚如雪哗咆。 梳的紋絲不亂的頭發(fā)上蜘欲,一...
    開封第一講書人閱讀 51,482評(píng)論 1 302
  • 那天,我揣著相機(jī)與錄音晌柬,去河邊找鬼姥份。 笑死郭脂,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的澈歉。 我是一名探鬼主播展鸡,決...
    沈念sama閱讀 40,271評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼埃难!你這毒婦竟也來了莹弊?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,166評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤涡尘,失蹤者是張志新(化名)和其女友劉穎忍弛,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體考抄,經(jīng)...
    沈念sama閱讀 45,608評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡细疚,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了座泳。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片惠昔。...
    茶點(diǎn)故事閱讀 39,926評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖挑势,靈堂內(nèi)的尸體忽然破棺而出镇防,到底是詐尸還是另有隱情,我是刑警寧澤潮饱,帶...
    沈念sama閱讀 35,644評(píng)論 5 346
  • 正文 年R本政府宣布来氧,位于F島的核電站,受9級(jí)特大地震影響香拉,放射性物質(zhì)發(fā)生泄漏啦扬。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評(píng)論 3 329
  • 文/蒙蒙 一凫碌、第九天 我趴在偏房一處隱蔽的房頂上張望扑毡。 院中可真熱鬧,春花似錦盛险、人聲如沸瞄摊。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽换帜。三九已至,卻和暖如春鹤啡,著一層夾襖步出監(jiān)牢的瞬間惯驼,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評(píng)論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留祟牲,地道東北人隙畜。 一個(gè)月前我還...
    沈念sama閱讀 48,063評(píng)論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像说贝,于是被迫代替她去往敵國和親禾蚕。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評(píng)論 2 354

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

  • 有啥不懂的或者出錯(cuò)的可以在下面留言狂丝。 1. 文件上傳 返回是String就是文件所在路徑,一般把它放到數(shù)據(jù)庫中哗总。我...
    FantJ閱讀 2,771評(píng)論 0 6
  • 項(xiàng)目中經(jīng)常會(huì)有上傳和下載的需求几颜,這篇文章簡述一下springboot項(xiàng)目中實(shí)現(xiàn)簡單的上傳和下載。 新建spring...
    dalaoyang閱讀 58,851評(píng)論 7 88
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,117評(píng)論 25 707
  • 用兩張圖告訴你讯屈,為什么你的 App 會(huì)卡頓? - Android - 掘金 Cover 有什么料蛋哭? 從這篇文章中你...
    hw1212閱讀 12,723評(píng)論 2 59
  • Day 7 斷舍離日 ?閱讀25min 配合主題還讀了《斷舍離 》 ?走路5000步 ?記賬 今天陪父母去照了全家...
    82阿岳北京2閱讀 204評(píng)論 0 0