element ui+spring boot上传文件并保存到数据库,数据库,前端和后端entity层,mapper层,service层,controller层详细代码该怎么写?
时间: 2024-03-05 21:51:14 浏览: 24
上传文件并保存到数据库,需要前端和后端配合完成。下面是详细的代码实现过程。
1. 前端代码
使用Element UI的el-upload组件上传文件,代码如下:
```
<template>
<el-upload
class="upload-demo"
action="/api/upload"
:on-success="handleSuccess"
:before-upload="beforeUpload">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</template>
<script>
export default {
methods: {
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
const isLt500K = file.size / 1024 < 500
if (!isJPG) {
this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
}
if (!isLt500K) {
this.$message.error('上传头像图片大小不能超过 500KB!')
}
return isJPG && isLt500K
},
handleSuccess(res) {
this.$emit('upload-success', res.data)
}
}
}
</script>
```
2. 后端代码
2.1 Entity层
定义一个File实体类,用于映射数据库表和上传的文件信息,代码如下:
```
@Entity
@Table(name = "file")
public class FileEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "type")
private String type;
@Lob
@Basic(fetch = FetchType.LAZY)
@Column(name = "data")
private byte[] data;
// getter and setter
}
```
2.2 Mapper层
定义一个FileMapper接口,继承自JpaRepository,并添加一个根据文件名查询的方法,代码如下:
```
public interface FileMapper extends JpaRepository<FileEntity, Long> {
FileEntity findByName(String name);
}
```
2.3 Service层
定义一个FileService接口和FileServiceImpl实现类,用于处理文件上传和保存到数据库的逻辑,代码如下:
```
public interface FileService {
FileEntity upload(MultipartFile file) throws IOException;
}
@Service
public class FileServiceImpl implements FileService {
@Autowired
private FileMapper fileMapper;
@Override
public FileEntity upload(MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
String fileType = file.getContentType();
byte[] fileData = file.getBytes();
FileEntity fileEntity = new FileEntity();
fileEntity.setName(fileName);
fileEntity.setType(fileType);
fileEntity.setData(fileData);
return fileMapper.save(fileEntity);
}
}
```
2.4 Controller层
定义一个FileController类,用于处理文件上传请求和返回上传文件的信息,代码如下:
```
@RestController
@RequestMapping("/api")
public class FileController {
@Autowired
private FileService fileService;
@PostMapping("/upload")
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) {
try {
FileEntity fileEntity = fileService.upload(file);
return ResponseEntity.ok().body(new ApiResponse(true, "文件上传成功!", fileEntity.getId()));
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.badRequest().body(new ApiResponse(false, "文件上传失败!"));
}
}
@GetMapping("/files/{id}")
public ResponseEntity<byte[]> getFile(@PathVariable Long id) {
FileEntity fileEntity = fileService.getFileById(id);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileEntity.getName() + "\"")
.body(fileEntity.getData());
}
}
```
3. 部署和测试
将前端代码和后端代码打包部署到服务器上,并启动后端服务。在浏览器中访问前端页面,选择一个文件上传,上传成功后会返回文件在数据库中的id。可以在数据库中查询文件是否上传成功,也可以通过访问`/api/files/{id}`接口下载文件。