源码地址
https://gitee.com/618859/java_springboot_upload_image
效果 核心代码
package com.example.java_springboot_uploadimg.controller;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.serializer.SerializerFeature;import org.springframework.boot.system.ApplicationHome;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.MultipartFile;import java.util.HashMap;import java.util.Map;import java.util.UUID;import com.alibaba.fastjson.JSONObject;import org.apache.commons.io.FileUtils;import java.io.File;import java.io.IOException;// 上传图片参考b站视频 https://www.bilibili.com/video/BV1TK41Z7ad/spm_id_from=333.337.search-card.all.click&vd_source=125d80bbad2b8400f21b16a0f64@RestControllerpublic class helloController { // 写入文件 private boolean writeFile(String content, String targetPath){ try { if(content != null){ // String json = JSONObject.toJSONString(content); File file = new File(targetPath); FileUtils.writeStringToFile(file, content,"UTF-8",false); return true; } }catch (IOException e){ System.out.println("error-writeFile: "+e); } return false; } // 读取文件 public JSONArray readFile(String filePath) throws IOException { File file = new File(filePath); String content = FileUtils.readFileToString(file,"UTF-8"); System.out.println("content:"+content); JSONArray arr = JSON.parseArray(content); System.out.println("jsonObject:"+arr); // System.out.println“姓名是:”+jsonObject.getString("name")); // System.out.println(年龄:"+jsonObject.getDouble("age")); // System.out.println(”学到的技能:"+jsonObject.getJSONArray("major")); // System.out.println“国家:”+jsonObject.getJSONObject("Nativeplace").getString("country")); return arr; } public String getJsonPath(){ String projectPath = this.getProjectPath(); projectPath = projectPath + "//src//main//resources//me.json"; return projectPath; } @GetMapping("/getData") public JSONArray getData() throws IOException { String projectPath = this.getJsonPath(); JSONArray object = this.readFile(projectPath); return object; } @PostMapping("/upload") public JSONArray upload(MultipartFile file) throws IOException { System.out.println(有人进来-); // 1.获取文件名 String fileName = file.getOriginalFilename(); Integer index = fileName.lastIndexOf("."); Integer pointIndex = fileName.length()-(fileName.length()-index); String name = fileName.substring(0,pointIndex); String etc = fileName.substring(pointIndex); System.out.println(后缀:"+etc); // 2.重命名文件,避免重复覆盖 String uuid = UUID.randomUUID().toString().replace""""; uuid = uuid.substring(0, 10); fileName = name+"_"+uuid+etc; System.out.println("fileName:"+fileName); // 3.获取要存储的路径 String targetPath = ""; targetPath = this.getProjectPath(); targetPath = targetPath + "//src//main//resources//static//images//" + fileName; // 4.写入文件 try{ file.transferTo(new File(targetPath)); // 读取json文件 String jsonPath = this.getJsonPath(); JSONArray arr = this.readFile(jsonPath); Map map = new HashMap(); map.put("name", name); map.put("img", "images/"+fileName); JSONObject obj = new JSONObject(map); arr.add(obj); System.out.println数据:“数据:”+arr); // 重写文件保存 SerializerFeature.PrettyFormat 是重点,格式化写入美 // 参考网址 https://www.jb51.net/article/197667.htm this.writeFile(JSONArray.toJSONString(arr, SerializerFeature.PrettyFormat), jsonPath); // 返回前端 return arr; } catch (IOException e){ e.printStackTrace(); } return new JSONArray(); } public String getProjectPath(){ ApplicationHome applicationHome = new ApplicationHome(this.getClass()); String targetPath = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath(); return targetPath; }}
依靠pom文件
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>java_springboot_uploadImg</artifactId> <version>0.0.1-SNAPSHOT</version> <name>java_springboot_uploadImg</name> <description>java_springboot_uploadImg</description> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring-boot.version>2.6.13</spring-boot.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>2.0.6</version> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>${spring-boot.version}</version> <configuration> <mainClass>com.example.java_springboot_uploadimg.JavaSpringbootUploadImgApplication</mainClass> <skip>true</skip> </configuration> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build></project>