共计 3083 个字符,预计需要花费 8 分钟才能阅读完成。
我们使用三个项目模拟三个服务器,完成图片回显
项目一(项目名: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:UsersAdministratorDesktop 上传文件 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,
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;
}
}
原文地址: HTML JQuery.ajax springboot 实现跨域上传图片并回显
正文完