Live-Server-8-SpringBoot文件上傳下載

服務(wù)器中的文件上傳下載是基本操作,圖片、用戶頭像的上傳下載、文件的傳輸和資源分享等已經(jīng)成為每個(gè)應(yīng)用必不可少的功能。在我的認(rèn)知中,服務(wù)器的文件存儲(chǔ)下載簡(jiǎn)單流程是這樣的:上傳文件->在數(shù)據(jù)庫中記錄該文件的相關(guān)信息(文件名、大小、路徑等)->提供文件列表->文件下載。

由于項(xiàng)目中只有App增量更新需要上傳和下載文件,那么這里就將文件的路徑固定。

上傳下載頁面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"></meta>
    <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>

上傳和下載控制器:

@RestController
public class FileController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private VersionService versionService;

    @RequestMapping(value = "/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return "文件為空";
            }
            //獲取文件名
            String fileName = file.getOriginalFilename();
            log.debug("上傳的文件名字:" + fileName);
            //獲取文件的后綴名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            log.debug("文件的后綴名為:" + suffixName);
            // 設(shè)置文件存儲(chǔ)路徑
            String filePath = "/usr/local/download/";
            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 = "/usr/local/download/";
            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 = "app_new.apk";
        if (fileName != null) {
            //設(shè)置文件路徑
            File file = new File("/usr/local/live/download/" + fileName);
            if (file.exists()) {
                response.setContentType("application/force-download"); //設(shè)置強(qiáng)制下載不打開
                //設(shè)置文件名
                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 "下載失敗";
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,694評(píng)論 1 32
  • ORA-00001: 違反唯一約束條件 (.) 錯(cuò)誤說明:當(dāng)在唯一索引所對(duì)應(yīng)的列上鍵入重復(fù)值時(shí),會(huì)觸發(fā)此異常。 O...
    我想起個(gè)好名字閱讀 6,037評(píng)論 0 9
  • 點(diǎn)擊查看原文 Web SDK 開發(fā)手冊(cè) SDK 概述 網(wǎng)易云信 SDK 為 Web 應(yīng)用提供一個(gè)完善的 IM 系統(tǒng)...
    layjoy閱讀 14,502評(píng)論 0 15
  • iOS開發(fā)系列--網(wǎng)絡(luò)開發(fā) 概覽 大部分應(yīng)用程序都或多或少會(huì)牽扯到網(wǎng)絡(luò)開發(fā),例如說新浪微博、微信等,這些應(yīng)用本身可...
    lichengjin閱讀 4,066評(píng)論 2 7
  • 我一直都相信緣分,能跟你相識(shí)、相知一定是緣分的安排。 你給我一種特殊的感覺,誰都沒有給過的。跟你在...
    總有不期而遇的溫暖閱讀 434評(píng)論 0 0

友情鏈接更多精彩內(nèi)容