我们使用三个项目模拟三个服务器,完成图片回显
项目一(项目名:uploadAndCORS):springboot项目,作为处理上传文件请求
项目二(项目名:uploadAndCORS-Front):上传文件页面
项目三(项目名:上传文件):保存文件目录
项目一:springboot项目,处理上传文件请求,并且配置CORS
项目总览
一、编写application.properties配置文件,主要是防止上传文件可能大于1MB因为springboot默认的上传文件最大值为1MB
server.port=8080
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB
复制
二、在主包创建一个config包,在config创建一个MyWebMvcConfig配置类来配置跨域策略。
package com.example.uploadandcors.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class MyWebMVCConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedHeaders("*") .allowedMethods("*") .maxAge(3600) .allowedOrigins("*"); } }
复制
三、在主包创建一个controller包,在controller包创建一个FileController控制器处理文件请求
package com.example.uploadandcors.controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; @RestController public class FileController { @PostMapping("/upload") public String uploadFile(@RequestParam(value = "file") MultipartFile file) { if (file.isEmpty()) { return "请选择文件上传"; } try { String url = "C:\\Users\\Administrator\\Desktop\\上传文件\\img\\"; File uploadFile = new File(url + file.getOriginalFilename()); file.transferTo(uploadFile); //这里的地址要注意是保存服务器运行起来的网络地址 return "http://127.0.0.1:5500/img/" + file.getOriginalFilename(); } catch (IOException e) { e.printStackTrace(); } return "上次失败"; } }
复制
项目二:上传文件页面
项目总览
一、将jquery的js文件导入进js目录,编写upload.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>上传图片,并将图片展示</title> <script src="js/jquery-3.6.0.min.js"></script> </head> <body> <input id="inputFile" type="file" name="file" value="请选择文件"> <button id="uploadBtn">点击上传</button> <img id="uploadImg" src="http://127.0.0.1:5500/img/猫猫.jpg"><br> <script> function uploadFile(){ var formData = new FormData() formData.append("file", document.getElementById("inputFile").files[0]) $.ajax({ type: "post", url: "http://localhost:8080/upload", data: formData, processData: false, contentType: false, cache: false, // dataType: "dataType", success: function (response) { console.log(response); $("#uploadImg").attr("src", response) } }); } $("#uploadBtn").click(function(event){ event.preventDefault(); uploadFile(); return false; }) </script> </body> </html>
复制
项目三:使用前端项目保存文件
项目总览
三个项目都运行起来
以下是随机命名文件名工具类(如需要不限制为图片文件可将判断图片)
package com.example.uploadandcors.util; import java.util.UUID; public class RandomFileNameUtil { public static String generateFileName(String originFileName){ String suffix = originFileName.substring(originFileName.lastIndexOf(".")); String[] imageExtensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp"}; boolean exists = Arrays.asList(imageExtensions).contains(suffix); if (!exists){ return "请上传图片"; } int index = originFileName.lastIndexOf("."); String newName = UUID.randomUUID().toString() + originFileName.substring(index); return newName; } }
复制