需求
前端上传图片至图床并返回图片地址给后端
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片上传测试</title>
</head>
<body>
<input type="file" id="uploadInput" />
<button onclick="uploadImage()">Upload</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function uploadImage() {
var fileInput = document.getElementById("uploadInput"); // 获取文件输入框
var file = fileInput.files[0]; // 获取用户选择的文件
var formData = new FormData();
formData.append("file", file); // 将文件添加到FormData对象中
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://api.superbed.cn/upload?token=您的token值"); // 设置请求方法和URL,token是Superbed提供的API Token
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
var imageUrl = response.url; // 获取上传后的图片地址
console.log("Image URL: " + imageUrl);
// 将获取到的图片链接传给后端,发送 POST 请求
$.ajax({
type: "POST",
url: "/upload",
data: {
imageUrl: imageUrl,
},
success: function (data) {
console.log(data);
},
error: function (xhr, status, error) {
console.log(xhr.responseText);
}
});
}
};
xhr.send(formData); // 发送请求,上传文件
}
</script>
</body>
</html>
后端代码
package com.starQeem.woha.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
- @Date: 2022/12/8 19:41
- @author: Qeem
*/
@Controller
public class testController {
@GetMapping("/upload")
public String test(){
return "test";
}
@PostMapping("/upload")
public String upload(@RequestParam("imageUrl") String imageUrl){
int i = 0;
return "redirect:/test";
}
}
这样后端就能拿到图片地址了:
评论区