0%

  在网上找了很多例子,不能完全契合自己的需求,自行整理了下。需求是这样的:项目小,所以不需要单独的图片服务器,图片保存在服务器中任意的地方,并且可以通过访问服务器来获取图片。话不多说上代码:

1、依赖

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<dependency>

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

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

</dependency>

<dependency>

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

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

</dependency>

<!-- apache.commons -->

<dependency>

<groupId>commons-lang</groupId>

<artifactId>commons-lang</artifactId>

<version>``2.6``</version>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>org.apache.commons</groupId>

<artifactId>commons-io</artifactId>

<version>``1.3``.``2``</version>

</dependency>

2、文件上传工具类

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

package com.slovi.utils;

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import org.apache.commons.io.FilenameUtils;

import org.apache.commons.io.IOUtils;

import org.springframework.web.multipart.MultipartFile;

public class FileUpload {

/**

* 文件上传处理

*

* @param file

* @return

*/

public static String writeUploadFile(MultipartFile file,String module) {

String filename = file.getOriginalFilename();

String realpath = "D:/rentHouse/" +  module +``"/"``;

File fileDir = new File(realpath);

if (!fileDir.exists())

fileDir.mkdirs();

String extname = FilenameUtils.getExtension(filename);

String allowImgFormat = "gif,jpg,jpeg,png"``;

if (!allowImgFormat.contains(extname.toLowerCase())) {

return "NOT_IMAGE"``;

}

filename = Math.abs(file.getOriginalFilename().hashCode()) + RandomUtils.createRandomString( 4 ) + "." + extname;

InputStream input = null``;

FileOutputStream fos = null``;

try {

input = file.getInputStream();

fos = new FileOutputStream(realpath + "/" + filename);

IOUtils.copy(input, fos);

} catch (Exception e) {

e.printStackTrace();

return null``;

} finally {

IOUtils.closeQuietly(input);

IOUtils.closeQuietly(fos);

}

return "/" + filename;

}

}

3、随机数生成工具类

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

package com.slovi.utils;

public class RandomUtils {

private static final String charlist = "0123456789"``;

public static String createRandomString(``int len) {

String str = new String();

for (``int i = 0``; i < len; i++) {

str += charlist.charAt(getRandom(charlist.length()));

}

return str;

}

public static int getRandom(``int mod) {

if (mod < 1``) {

return 0``;

}

int ret = getInt() % mod;

return ret;

}

private static int getInt() {

int ret = Math.abs(Long.valueOf(getRandomNumString()).intValue());

return ret;

}

private static String getRandomNumString() {

double d = Math.random();

String dStr = String.valueOf(d).replaceAll(``"[^\\d]"``, ""``);

if (dStr.length() > 1``) {

dStr = dStr.substring(``0``, dStr.length() - 1``);

}

return dStr;

}

}

4、控制类

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

package com.slovi.controller;

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

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

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

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

import org.springframework.web.multipart.MultipartFile;

import com.slovi.utils.FileUpload;

@RestController

@RequestMapping``(``"/Advert"``)

public class AdvertController {

@Autowired

private AdvertInfoService advertInfoService;

@PostMapping``(``"/upload"``)

public Object upload(``@RequestParam``(``"file"``) MultipartFile  file) {

String filename = FileUpload.writeUploadFile(file,``"advert"``);

return filename;

}

}

5、配置类

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

package com.slovi.config;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration

public class WebMvcConfig implements WebMvcConfigurer {

@Override

public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler(``"/static/**"``).addResourceLocations(``"classpath:/static/"``);

registry.addResourceHandler(``"/advertIMG/**"``).addResourceLocations(``"file:D:/rentHouse/"``);

}

}

6、测试页面,放到resources/templates包下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<!DOCTYPE html>

<html lang=``"en" xmlns:th=``"http://www.thymeleaf.org"``>

<head>

<meta charset=``"UTF-8"``/>

<title>Title</title>

</head>

<body>

<form action=``"/upload" th:action=``"@{/upload}" method=``"post" enctype=``"multipart/form-data" >

<label>上传图片</label>

<input type=``"file" name=``"file"``/>

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

</form>

</body>

</html>

  启动项目,访问:localhost:8888,进入上传页面,上传成功会返回图片名称,例如:11348371257146.jpg,然后访问http://localhost:8888/advertIMG/11348371257146.jpg,可以获取到图片。