在网上找了很多例子,不能完全契合自己的需求,自行整理了下。需求是这样的:项目小,所以不需要单独的图片服务器,图片保存在服务器中任意的地方,并且可以通过访问服务器来获取图片。话不多说上代码:
1、依赖
org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-thymeleaf commons-lang commons-lang 2.6 provided org.apache.commons commons-io 1.3.2
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;@Configurationpublic 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包下
Title
启动项目,访问:localhost:8888,进入上传页面,上传成功会返回图片名称,例如:11348371257146.jpg,然后访问http://localhost:8888/advertIMG/11348371257146.jpg,可以获取到图片。