前端發(fā)送圖片
1. HTML代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>上傳圖片</title>
</head>
<body>
<input type="file" id="fileInput">
<button onclick="uploadImage()">上傳圖片</button>
<script>
function uploadImage() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const formData = new FormData();
formData.append('image', file);
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
}
</script>
</body>
</html>2. JavaScript代碼
在上面的HTML代碼中,我們創(chuàng)建了一個(gè)文件輸入框和一個(gè)上傳按鈕。當(dāng)用戶點(diǎn)擊上傳按鈕時(shí),會(huì)觸發(fā)"uploadImage"函數(shù)。這個(gè)函數(shù)首先獲取文件輸入框中的文件,然后將文件添加到"FormData"對(duì)象中。最后,使用"fetch"方法向服務(wù)器發(fā)送一個(gè)POST請(qǐng)求,將圖片數(shù)據(jù)作為請(qǐng)求體發(fā)送。
Java后端接收?qǐng)D片并處理
1. 首先,我們需要在Spring Boot項(xiàng)目中創(chuàng)建一個(gè)新的控制器類,用于處理前端發(fā)送的圖片請(qǐng)求。在這個(gè)例子中,我們將其命名為"ImageController"。以下是"ImageController"的代碼:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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;
@RestController
public class ImageController {
@PostMapping("/upload")
public ResponseEntity<?> uploadImage(@RequestParam("image") MultipartFile image) {
// 對(duì)圖片進(jìn)行處理的代碼可以放在這里,例如保存到服務(wù)器、裁剪、縮放等操作
System.out.println("收到圖片大?。?" + image.getSize() + "字節(jié)");
return new ResponseEntity<>("圖片上傳成功", HttpStatus.OK);
}
}2. 在上面的代碼中,我們定義了一個(gè)名為"uploadImage"的方法,該方法使用"@PostMapping"注解映射到"/upload"路徑。這個(gè)方法接收一個(gè)名為"image"的參數(shù),該參數(shù)是一個(gè)"MultipartFile"對(duì)象,表示前端發(fā)送的圖片文件。我們可以在方法內(nèi)部對(duì)這個(gè)文件進(jìn)行處理,例如保存到服務(wù)器、裁剪、縮放等操作。在這個(gè)例子中,我們只是簡(jiǎn)單地打印了圖片的大小。如果處理成功,我們返回一個(gè)包含成功信息的響應(yīng)實(shí)體。
3. 最后,我們需要在項(xiàng)目的主類上添加"@ComponentScan"注解,以便讓Spring Boot自動(dòng)掃描并注冊(cè)我們的控制器類。以下是我們的主類代碼:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@ComponentScan(basePackages = {"com.example"}) // 這里替換為你的包名
public class ImageProcessingApplication {
public static void main(String[] args) {
SpringApplication.run(ImageProcessingApplication.class, args);
}
}現(xiàn)在,當(dāng)你運(yùn)行這個(gè)項(xiàng)目并訪問前端頁面時(shí),選擇一張圖片并點(diǎn)擊上傳按鈕,Java后端就會(huì)接收到這張圖片并執(zhí)行相應(yīng)的處理操作。你可以根據(jù)需要修改"ImageController"中的代碼,實(shí)現(xiàn)更多的多媒體數(shù)據(jù)處理功能。