1.导入依赖
java
复制代码
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
2、后端代码
java
复制代码
private static String fileUrl = "D:/software/nginx-1.23.4/html/";
public String upload(@RequestBody UploadInfo uploadInfo) {
String name = uploadInfo.getName();
String[] imgData = StrUtil.splitToArray(uploadInfo.getBase64(), "base64,");
byte[] bytes = Base64.decode(imgData[1]);
name = IdUtil.fastSimpleUUID() + "_" + name;
FileUtil.writeBytes(bytes,"D:/software/nginx-1.23.1/html/images/"+name);
String ext = FileUtil.getSuffix(name);
switch (ext) {
case "mp4":
fileUrl = fileUrl + "video/"+name;
break;
default: ;
fileUrl = fileUrl + "images/"+name;
break;
}
return "http://img.207.com/images/"+name;
}
3.前端代码
java
复制代码
const onChange = (uploadFile: any, uploadFiles: any) => {
uploadData.name = uploadFile.name
console.log(uploadData.name)
const file = uploadFile.raw
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => {
uploadData.base64 = reader.result
callUploadApi()
}
}
const callUploadApi = () => {
uploadApi.upload.call({ name: uploadData.name, base64: uploadData.base64 }).then((res: any) => {
imageUrl.value = getFileImg(res.data)
})
}
const getFileImg = (url: string) => {
let ext = url.split('.')[url.split('.').length - 1]
switch (ext) {
case "xlsx":
return "data:image/png;base64,xxxx"
break;
default:
return url
}
}
</script>
4.使用原生javascript
java
复制代码
<input type="file" onchange="upload(event)">
<script>
function upload(e) {
let file = e.target.files[0];
let reader = new FileReader()
reader.readAsDataURL(file)
reader.onload = () => {
console.log(reader.result);
}
}
</script>