Spring boot 实现单个或批量文件上传功能(很实用,最常用)

一:添加依赖:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

<!-- thymeleaf模板插件 -->

  <dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-thymeleaf</artifactId>

  </dependency>

   <!-- jsp依赖 -->

<dependency>

  <groupId>javax.servlet</groupId>

  <artifactId>jstl</artifactId>

</dependency>

<dependency>

  <groupId>org.apache.tomcat.embed</groupId>

  <artifactId>tomcat-embed-jasper</artifactId>

  <!--<scope>provided</scope>-->

</dependency>

二:application.xml配置文件路径:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

#配置上传文件地址(务必使用绝对路径,否则会带来麻烦,参考https://blog.csdn.net/HD243608836/article/details/103715056

image.location.path=f:/image/

#配置文件大小限制

spring.http.multipart.maxFileSize=100Mb

spring.http.multipart.maxRequestSize=100Mb

#静态页面的访问配置

spring.thymeleaf.cache=false

spring.thymeleaf.prefix=classpath:/templates/

spring.thymeleaf.check-template-location=true

spring.thymeleaf.suffix=.html

spring.thymeleaf.encoding=UTF-8

spring.thymeleaf.content-type=text/html

spring.thymeleaf.mode=HTML5

三:编写静态页面(src/main/resources下建文件夹static(static存放静态文件,比如 css、js、image…)和templates(存放静态页面)两个是同级目录),先在templates 中新建一个 uploadimg.html。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<!DOCTYPE html>

<html>

 <head>

  <title>uploadimg.html</title>

  <meta name="keywords" content="keyword1,keyword2,keyword3"></meta>

  <meta name="description" content="this is my page"></meta>

  <meta name="content-type" content="text/html; charset=UTF-8"></meta>

  <!--<link rel="stylesheet" type="text/css" href="./styles.css" rel="external nofollow" >-->

 </head>

 <body>

 <form enctype="multipart/form-data" method="post" action="/dc/fileUpload">

  图片<input type="file" name="file"/>

  <input type="submit" value="上传"/>

  </form>

 </body>

</html>

四:编写Controller层:

?

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

135

136

137

138

139

140

141

142

143

144

package com.hot.analysis.controller.file;

import java.io.BufferedInputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.util.Date;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.servlet.ModelAndView;

import com.hot.analysis.exception.MyException;

@RestController

public class FileUploadController {

 //获取配置文件的路径(这种方式最常用)

 @Value("${image.location.path}")

 private String resourceDir;

 /**

   * 实现文件上传

   * */

 @RequestMapping(value = "/index")

 public ModelAndView toIndex() {

 ModelAndView mv = new ModelAndView("uploadimg");

 return mv;

 }

  //单个文件上传

  @RequestMapping("/dc/fileUpload")

  @ResponseBody

  public String fileUpload( MultipartFile file){

   // 获取上传文件路径

    String uploadPath = file.getOriginalFilename();

    // 获取上传文件的后缀

    String fileSuffix = uploadPath.substring(uploadPath.lastIndexOf(".") + 1, uploadPath.length());

    if (fileSuffix.equals("apk")) {

    uploadPath = resourceDir;

    } else {

    // 上传目录地址

    // String uploadpath="E:/hot-manage/image/";//windows路径

    uploadPath =resourceDir;// liux路劲

    }

    // 上传文件名

    String fileName = new Date().getTime() + new Random().nextInt(100) + "." + fileSuffix;

    File savefile = new File(uploadPath + fileName);

    if (!savefile.getParentFile().exists()) {

    savefile.getParentFile().mkdirs();

    }

    try {

    file.transferTo(savefile);

    } catch (IllegalStateException e) {

    e.printStackTrace();

    } catch (IOException e) {

    e.printStackTrace();

    }

    if (fileSuffix.equals("apk")) {

    return "/apk/" + fileName;

    } else {

    return "/image/" + fileName;

    }

   }

 // 批量上传

  @PostMapping("/dc/moreFileUpload")

 public String bacthFileUpload(MultipartFile[] file) throws MyException {

  StringBuffer buffer = new StringBuffer();

  for (MultipartFile multipartFile : file) {

  String str = fileUpload(multipartFile);

  buffer.append(str);

  buffer.append(",");

  }

  String all = buffer.substring(0, buffer.length() - 1);

  return all;

 }

 // 删除文件

  @PostMapping("/dc/deleteFile")

  public String delFile(String path) {

   String resultInfo = null;

 int lastIndexOf = path.lastIndexOf("/");

 String sb = path.substring(lastIndexOf + 1, path.length());

 sb = "f:/image/" + sb;

 File file = new File(sb);

 if (file.exists()) {

  if (file.delete()) {

  resultInfo = "1-删除成功";

  } else {

  resultInfo = "0-删除失败";

  }

 } else {

  resultInfo = "文件不存在!";

 }

 return resultInfo;

 }

 //文件下载相关代码

  @RequestMapping("/download")

  public String downloadFile(HttpServletRequest request, HttpServletResponse response) {

    String fileName = "aim_test.txt";// 设置文件名,根据业务需要替换成要下载的文件名

    if (fileName != null) {

      //设置文件路径

      String realPath = "D://aim//";

      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;

  }

 

  }

测试:

 

成功返回路径:

 

查看文件夹:

 

 

转载自:https://www.jb51.net/article/145827.htm

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值