1.前端
<!doctype html>
<html lang="en">
<head>
<title>html调用摄像头--拍照--上传</title>
<meta charset="utf-8">
<script src="axios.min.js"></script>
</head>
<body>
<table>
<tr>
<td><video id="video" width="500px" autoplay="autoplay"></video></td>
<td><canvas id="canvas" width="500px" height="375px"></canvas></td>
</tr>
<tr>
<td align="right"><button onclick="takePhoto()">拍照</button></td>
<td align="right"><button onclick="fileUp()">上传</button></td>
</tr>
</table>
</body>
<script>
//打开摄像头
navigator.mediaDevices.getUserMedia({video:{width:500}}).then((stream)=> video.srcObject = stream);
//拍照
function takePhoto() {
canvas.getContext('2d').drawImage(video, 0, 0, 500, 375);
}
//上传
function fileUp() {
canvas.toBlob((data)=>{
let formData = new FormData();
formData.append("file",data,"face.jpg");
axios.post('/upload',formData,{'Content-type' : 'multipart/form-data' }).then(res=>{
console.log("上传成功!",res.data);
alert(res.data.message);
},err=>{
console.log("上传失败!");
});
},"image/jpeg",1);
}
</script>
</html>
2后端
package com.gzz.controller;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Map;
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;
/**
* @summary https://www.jianshu.com/u/3bd57d5f1074
* @author 高振中
* @date 2022-12-06 11:18:20
**/
@RestController
public class UploadController {
@PostMapping("/upload")
public Map<String, String> singleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
return Map.of("message", "Please select a file to upload!");
}
Path path = Paths.get("D:/temp/", file.getOriginalFilename());
file.transferTo(path);
return Map.of("message", "OK", "path", path.toString());
}
}
网友评论