springboot 上传文件解析入库_SpringBoot文件上传下载和多文件上传(图文详解)

最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的Java代码:

1、开发环境:

IDEA15+ Maven+JDK1.8

2、新建一个maven工程:

3、工程框架

4、pom.xml文件依赖项

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

4.0.0

SpringWebContent

SpringWebContent

war

1.0-SNAPSHOT

SpringWebContent Maven Webapp

http://maven.apache.org

org.springframework.boot

spring-boot-starter-parent

1.4.3.RELEASE

org.springframework.boot

spring-boot-starter-thymeleaf

org.springframework.boot

spring-boot-devtools

true

junit

junit

3.8.1

test

1.8

SpringWebContent

org.springframework.boot

spring-boot-maven-plugin

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

441

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

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);

}

}1

2

3

4

5

6

7

8

91

2

3

4

5

6

7

8

9

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 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";

}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

1341

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

7、index.html

Getting Started: Serving Web Content

Get your greeting here

文件:

下载test

多文件上传

文件1:

文件2:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

211

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

在Spring Boot中,处理文件上传解析入库的过程可以通过以下步骤实现: 1. 首先,你可以在Spring Boot项目中创建一个Controller类,并使用`@PostMapping`注解将一个URL映射到该方法上,以接收上传文件的请求。 2. 在Controller方法的参数中,你可以使用`@RequestParam`注解来获取上传的文件,并将其保存到服务器上的指定路径中。可以使用以下代码来获取上传文件并保存: ```java @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { try { // 获取上传文件的原始文件名 String fileName = file.getOriginalFilename(); // 指定文件保存的路径 String filePath = "/upload/"; // 创建保存文件的目录 File saveDir = new File(filePath); if (!saveDir.exists()) { saveDir.mkdirs(); } // 创建保存文件的完整路径 File saveFile = new File(saveDir.getAbsolutePath() + File.separator + fileName); // 将上传文件保存到指定路径 file.transferTo(saveFile); // 文件保存成功后,将文件信息解析入库或进行其他操作 return "File uploaded successfully"; } catch (Exception e) { // 处理文件上传过程中的异常 return "File upload failed"; } } ``` 在上面的代码中,`handleFileUpload`方法接收一个`MultipartFile`类型的参数来获取上传的文件。通过`file.getOriginalFilename()`可以获得上传文件的原始文件名。然后,我们可以指定文件保存的路径,并创建保存文件的目录。最后,使用`file.transferTo(saveFile)`将上传文件保存到指定路径。 3. 在文件保存成功后,你可以对文件进行解析入库操作,具体的操作步骤根据你的业务需求而定。 注意:在进行文件上传之前,需要确保在Spring Boot的配置文件中配置了相应的文件上传配置。例如,可以使用`multipart.enabled=true`来启用文件上传功能。这可以通过在`application.properties`或`application.yml`文件中进行配置来实现。 以上就是在Spring Boot中处理文件上传解析入库的基本步骤。你可以根据实际需求进行相应的调整和扩展。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [SpringBoot实现文件上传](https://blog.csdn.net/weixin_34194829/article/details/112867169)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [SpringBoot实现文件上传功能详解](https://blog.csdn.net/weixin_35025136/article/details/112046172)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值