激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語(yǔ)言|JavaScript|易語(yǔ)言|vb.net|

服務(wù)器之家 - 編程語(yǔ)言 - Java教程 - 詳解SpringBoot文件上傳下載和多文件上傳(圖文)

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

2020-08-20 11:08Coding13 Java教程

本篇文章主要介紹了詳解SpringBoot文件上傳下載和多文件上傳(圖文),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。

最近在學(xué)習(xí)SpringBoot,以下是最近學(xué)習(xí)整理的實(shí)現(xiàn)文件上傳下載的Java代碼:

1、開(kāi)發(fā)環(huán)境:

IDEA15+ Maven+JDK1.8

2、新建一個(gè)maven工程:

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

3、工程框架

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

4、pom.xml文件依賴項(xiàng)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<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

?
1
2
3
4
5
6
7
8
9
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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
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);
  //文件上傳相關(guān)代碼
  @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//";
    // 解決中文問(wèn)題,liunx下中文路徑,圖片顯示問(wèn)題
    // fileName = UUID.randomUUID() + suffixName;
    File dest = new File(filePath + fileName);
    // 檢測(cè)是否存在目錄
    if (!dest.getParentFile().exists()) {
      dest.getParentFile().mkdirs();
    }
    try {
      file.transferTo(dest);
      return "上傳成功";
    } catch (IllegalStateException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return "上傳失敗";
  }
 
  //文件下載相關(guān)代碼
  @RequestMapping("/download")
  public String downloadFile(org.apache.catalina.servlet4preview.http.HttpServletRequest request, HttpServletResponse response){
    String fileName = "FileUploadTests.java";
    if (fileName != null) {
      //當(dāng)前是從該工程的WEB-INF//File//下獲取文件(該目錄可以在下面一行代碼配置)然后下載到C:\\users\\downloads即本機(jī)的默認(rèn)下載的目錄
      String realPath = request.getServletContext().getRealPath(
          "//WEB-INF//");
      File file = new File(realPath, fileName);
      if (file.exists()) {
        response.setContentType("application/force-download");// 設(shè)置強(qiáng)制下載不打開(kāi)
        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);
          }
          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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!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" rel="external nofollow" >here</a></p>
<form action="/upload" method="POST" enctype="multipart/form-data">
  文件:<input type="file" name="test"/>
  <input type="submit" />
</form>
<a href="/download" rel="external nofollow" >下載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>

完整工程地址:SpringWebContent.rar

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:http://blog.csdn.net/coding13/article/details/54577076

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 免费在线性爱视频 | 婷婷久久综合九色综合色多多蜜臀 | 91成人免费在线观看 | 国产一级中文字幕 | 成年人小视频在线观看 | 九九热这里只有精品8 | 欧美性生交大片 | 久久精品视频免费 | qyl在线视频精品免费观看 | 久久精品亚洲精品国产欧美kt∨ | 成人免费毛片一 | 午夜a狂野欧美一区二区 | 日韩免费黄色 | 国产视频在线免费观看 | 亚洲片在线观看 | 亚洲第一色婷婷 | 国产美女视频黄a视频免费 日韩黄色在线播放 | 视频一区二区三区在线 | 久久精品.com| 免费看日产一区二区三区 | 性 毛片 | 国产成人羞羞视频在线 | 国产亚洲精品久久久久久久久 | 毛毛片在线看 | 美女擦逼| 欧美精品一区二区三区四区 | 精品国产一区二区三区四区阿崩 | 久色成人 | 精品一区二区三区中文字幕老牛 | 亚洲人成综合第一网 | 性生活视频软件 | 91成人影院 | 免费观看一区二区三区 | 免费午夜视频在线观看 | 国产乱色精品成人免费视频 | 国产精品一区在线看 | 午夜视频在线免费观看 | 91精品国产99久久久久久 | www.91sp| 国产成人在线观看网站 | 久久亚洲精选 |