spring-boot上传图片并访问
一、maven
<!-- 引入json处理包 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.35</version> </dependency> <!--IO 文件流需要的包--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
二、application.yml
server: port: 8080 spring: servlet: multipart: {max-request-size: 100MB, max-file-size: 100MB } # max-request-size上传文件总的最大值, multipart.max-file-size单个文件的最大值 file: staticAccessPath: /static/upload/img/** # 静态资源对外暴露的访问路径 uploadFolder: F:/upload/ #文件上传目录(注意Linux和Windows上的目录结构不同)
三、java代码
1). 实现WebMvcConfigurer接口(主要做静态资源目录映射)
import org.springframework.beans.factory.annotation.Value; 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 UploadFilePathConfig implements WebMvcConfigurer { @Value("${file.staticAccessPath}") private String staticAccessPath; @Value("${file.uploadFolder}") private String uploadFolder; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder); } }
2).RandomUtils生成随机数的类
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; } }
3.MyCommon上传文件的工具类
import org.apache.commons.io.FilenameUtils; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.lang.NonNull; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.util.HashMap; import java.util.Map; public class MyCommon { private static Map<String, File> dirMap = new HashMap<>(); /** * 上传图片 * @param file 文件流对象 * @param realpath 文件存放路径 * @return */ public static String inputUploadFile(MultipartFile file, String realpath) { String filename = file.getOriginalFilename();//文件名createFileName(file.getOriginalFilename());// File dir = getDir(realpath); 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; } private static String createFileName(String filename) {//重新改变文件名 //FilenameUtils.getExtension(filename);//文件扩展名 String dataReadom = String.valueOf(Math.floor(System.currentTimeMillis() / 1000)); dataReadom += RandomUtils.createRandomString(6); return dataReadom + FilenameUtils.getExtension(filename); } /** * 判断目录是否存在不存在则创建目录 * @param dirName * @return */ private static File getDir(@NonNull String dirName) { File dir = dirMap.get(dirName); if (dir != null) { return dir; } dir = new File(dirName); if (!dir.exists()) { dir.mkdirs(); } dirMap.put(dirName, dir); return dir; } /** * 获取网站域名地址 * @param request * @return */ public static String domain(HttpServletRequest request) { String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();// + path; return basePath; } }
四、编写一个测试上传文件helloworld(HelloTest类)
import com.alibaba.fastjson.JSONObject; import com.example.hello2.clacc.MyCommon; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.ResourceUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.FileNotFoundException; @RestController @RequestMapping(path = "/", produces = "application/json;charset=UTF-8") public class HelloTest { @Value("${file.uploadFolder}") private String uploadFolder; private String staticAccessPath = "/static/upload/img/"; private JSONObject result; @RequestMapping(path = "/fileload") public String Upload(MultipartFile file, HttpServletRequest request) throws FileNotFoundException { String domain = MyCommon.domain(request); String basePath = ResourceUtils.getURL("classpath:").getPath(); String fileStr = MyCommon.inputUploadFile(file, uploadFolder); result = new JSONObject(); if (fileStr.equals("NOT_IMAGE")) { result.put("msg", "上传失败"); result.put("data", fileStr); result.put("status", 301); } else { result.put("msg", "上传成功"); result.put("data", domain + staticAccessPath + fileStr); result.put("status", 200); } return result.toJSONString(); } }
五、测试图
1).postman测试
2).本地目录
3).浏览器访问
附一、 上传多图其实也是这样只是接收参数改成集合的方式接收
1). 控制器
/**上传多张图片**/ @PostMapping(path = "/uploadimgs") public String uploadImgs(@RequestParam("file") List<MultipartFile> files, HttpServletRequest request) throws FileNotFoundException { dataJson = new JSONObject(); String basePath = ResourceUtils.getURL("classpath:").getPath(); List<String> filesStr = MyCommon.inputUploadFiles(files, saveImgPath); dataJson = new JSONObject(); if (filesStr.size() < 1) { dataJson.put("msg", "上传失败"); dataJson.put("data", filesStr); dataJson.put("status", 301); } else { dataJson.put("msg", "上传成功"); dataJson.put("data", filesStr); dataJson.put("status", 200); } return dataJson.toJSONString(); }
2.在MyCommon类中添加一个inputUploadFiles方法
public static List<String> inputUploadFiles(List<MultipartFile> files, String realpath) { List<String> listFile = new ArrayList<>(); for (MultipartFile file : files) { String fileStr = MyCommon.inputUploadFile(file, realpath); if(!fileStr.equals("NOT_IMAGE")){ listFile.add(fileStr); } } return listFile; }
inputUploadFiles