效果
Video_20230103022111[00-00-00--00-00-16].gif
pom.xml依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
前端页面
<template>
<el-upload class="upload-demo"
action=""
:auto-upload="false"
multiple="true"
:on-change="onchange">
<template #trigger>
<el-button type="primary">选择文件</el-button>
</template>
<el-button class="ml-3" type="success" @click="submitUpload">
上传
</el-button>
<template #tip>
<div class="el-upload__tip">
jpg/png files with a size less than 500kb
</div>
</template>
</el-upload>
</template>
<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
//保存要上传的文件
let myFiles = ref([])
//选择文件
let onchange = (file) => {
myFiles.value.push(file.raw)
console.log('-------------' + myFiles.value)
}
//上传文件
const submitUpload = () => {
//跟表单一起上传
//let formData = new FormData();
// for (let i = 0; i < myFiles.value.length; i++) {
// formData.append('myFiles', myFiles.value[i]);
//}
//formData.append('username', insertUser.value.username);
// formData.append('userpass', insertUser.value.userpass);
//一个一个上传
for (let i = 0; i < myFiles.value.length; i++) {
//手动添加表单,将文件追加到表单里
let fd = new FormData();
fd.append('myFiles', myFiles.value[i])
axios({
url: 'http://localhost:8088/fileUpload/uploadtodisk', //上传服务器接口
//url: 'http://localhost:8088/fileUpload/uploadtodatabase', //上传数据库接口
method: 'post',
data: fd,
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then((res) => {
if (res.data == 'ok') {
ElMessage({
message: '上传成功.',
type: 'success',
})
} else {
ElMessage({
message: '上传失败.',
type: 'warning',
})
}
})
}
}
</script>
后台controller
package com.neusoft.humanresources.controller;
import com.neusoft.humanresources.po.User;
import com.neusoft.humanresources.service.UserService;
import org.springframework.web.bind.annotation.RequestBody;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UserController {
@Autowired
UserService userService;
@ResponseBody
@PostMapping("/uploadtodisk")
public String uploadtodisk(MultipartFile myFiles, HttpServletRequest request) throws IOException {
System.out.println("上传到服务器目录");
// 服务器上对应存放图片的路径
String path = request.getServletContext().getRealPath("images");
// 上传到服务器的新文件名
String newFileName = UUID.randomUUID()
+ myFiles.getOriginalFilename().substring(myFiles.getOriginalFilename().lastIndexOf("."));
// 上传到服务器,返回前端结果
return uploadFile(path, newFileName, myFiles);
}
// 上传服务器方法
public String uploadFile(String path, String newFileName, MultipartFile myFile) {
File targetFile = new File(path + File.separator + newFileName);
try {
myFile.transferTo(targetFile);
return "ok";
} catch (Exception e) {
return "error";
}
}
//------------------------------------------------------------------------------------------
@ResponseBody
@PostMapping("/uploadtodatabase")
public String uploadtodatabase(MultipartFile myFiles) {
System.out.println("上传到数据库");
try {
// 向数据库上传Base64格式图片
String upic = getImageStr(myFiles.getInputStream());
System.out.println("Base64编码之后:" + upic);
userService.insertUser(new User(null, "zhangsan",upic, 20));
return "ok";
} catch (IOException e) {
e.printStackTrace();
return "error";
}
}
// 向数据库上传Base64格式图片
private String getImageStr(InputStream inputStream) {
byte[] data = null;
try {
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// 编码
Encoder encoder = Base64.getEncoder();
return encoder.encodeToString(data);
}
//获取头像
@ResponseBody
@PostMapping("/gettodatabase")
public User gettodatabase(@RequestBody User user){
System.out.println(user);
return userService.gettodatabase(user.getUserId());
}
}
读取的话
<template>
<div class="home">
<div class="block" >
<el-avatar :size="50" :src="circleUrl" />
</div>
</div>
</template>
<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
axios.defaults.withCredentials=true;
let circleUrl = ref("")
let user = ref({
userId:1
})
axios.post( 'http://localhost:8089/humanresources/gettodatabase',user.value)
.then((res) => {
console.log(res)
if (res.data != null) {
ElMessage({
message: '获取成功.',
type: 'success',
})
circleUrl.value = 'data:image/png;base64,'+res.data.userPic;
} else {
ElMessage({
message: '获取失败.',
type: 'warning',
})
}
})
</script>
user对象
@Data
public class User {
Integer userId;
String userName;
String userPic;
Integer userAge;
}
UserMapper
@Mapper
public interface UserMapper {
@Insert("insert into user(userId,userName,userPic,userAge) values(#{userId},#{userName},#{userPic},#{userAge})")
void insertUser(User user);
@Select("select * from user where userId=#{userId}")
User gettodatabase(Integer userId);
}
user表
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`userId` int NOT NULL AUTO_INCREMENT,
`userName` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL,
`userPic` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL,
`userAge` int NULL DEFAULT NULL,
PRIMARY KEY (`userId`) USING BTREE
)
网友评论