用springboot,vue,mybatis和elementUI实现上传文件到数据库
时间: 2023-05-20 15:05:33 浏览: 261
Java微信小程序商城系统源码+数据库,后台:springboot+mybatis+redi,前端:vue+element ui
5星 · 资源好评率100%
可以使用Spring Boot提供的MultipartFile类来处理文件上传,然后使用MyBatis将文件存储到数据库中。Vue和ElementUI可以用来实现前端页面和文件上传的交互。以下是一个简单的示例代码:
后端代码:
```
@RestController
public class FileController {
@Autowired
private FileService fileService;
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
fileService.saveFile(file);
return "File uploaded successfully!";
} catch (Exception e) {
return "Failed to upload file: " + e.getMessage();
}
}
}
@Service
public class FileService {
@Autowired
private FileMapper fileMapper;
public void saveFile(MultipartFile file) throws IOException {
FileEntity fileEntity = new FileEntity();
fileEntity.setName(file.getOriginalFilename());
fileEntity.setContent(file.getBytes());
fileMapper.insert(fileEntity);
}
}
@Mapper
public interface FileMapper {
@Insert("INSERT INTO file(name, content) VALUES(#{name}, #{content})")
void insert(FileEntity fileEntity);
}
public class FileEntity {
private Long id;
private String name;
private byte[] content;
// getters and setters
}
```
前端代码:
```
<template>
<div>
<input type="file" @change="uploadFile">
</div>
</template>
<script>
export default {
methods: {
uploadFile(event) {
const file = event.target.files[0];
const formData = new FormData();
formData.append('file', file);
axios.post('/upload', formData).then(response => {
console.log(response.data);
}).catch(error => {
console.error(error);
});
}
}
}
</script>
```
注意:这只是一个简单的示例,实际应用中还需要考虑文件大小限制、文件类型限制、文件名重复等问题。
阅读全文