1. 程式人生 > >SpringBoot檔案上傳下載和多檔案上傳(圖文詳解)

SpringBoot檔案上傳下載和多檔案上傳(圖文詳解)

最近在學習SpringBoot,以下是最近學習整理的實現檔案上傳下載的java程式碼:
1、開發環境:
IDEA15+ Maven+JDK1.8
2、新建一個maven工程:
這裡寫圖片描述
3、工程框架
這裡寫圖片描述
4、pom.xml檔案依賴項

<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);
    //檔案上傳相關程式碼
    @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//";
        // 解決中文問題,liunx下中文路徑,圖片顯示問題
        // fileName = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        // 檢測是否存在目錄
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return "上傳成功";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上傳失敗";
    }

    //檔案下載相關程式碼
    @RequestMapping("/download")
    public String downloadFile(org.apache.catalina.servlet4preview.http.HttpServletRequest request, HttpServletResponse response){
        String fileName = "FileUploadTests.java";
        if (fileName != null) {
            //當前是從該工程的WEB-INF//File//下獲取檔案(該目錄可以在下面一行程式碼配置)然後下載到C:\\users\\downloads即本機的預設下載的目錄
            String realPath = request.getServletContext().getRealPath(
                    "//WEB-INF//");
            File file = new File(realPath, fileName);
            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);
                    }
                    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">here</a></p>
<form action="/upload" method="POST" enctype="multipart/form-data">
    檔案:<input type="file" name="test"/>
    <input type="submit" />
</form>
<a href="/download">下載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>

以下是我的個人公眾號,主要作為C/C++語言技術分享使用,該公眾號裡乾貨滿滿,如果您有對此博文的疑問或者java方面的問題也可以新增公眾號交流討論。最後,再次希望您能新增關注,互相交流互相學習共同進步:

這裡寫圖片描述