在網上找了很多例子,不能完全契合自己的需求,自行整理了下。需求是這樣的:項目小,所以不需要單獨的圖片服務器,圖片保存在服務器中任意的地方,並且可以通過訪問服務器來獲取圖片。話不多說上代碼:
1、依賴
<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、文件上傳工具類
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、隨機數生成工具類
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、控制類
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、配置類
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包下
<!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,可以獲取到圖片。
