用springboot,vue,mybatis和elementUI实现上传PDF文件到数据库,需要上传到数据库的内容有文件名,文件上传时间,文件路径,上传者的编号。请给我实体类代码,控制器代码,服务类代码,实现类代码,前端代码,mybatis代码和数据库建表语句
时间: 2023-05-20 11:05:46 浏览: 91
Java微信小程序商城系统源码+数据库,后台:springboot+mybatis+redi,前端:vue+element ui
5星 · 资源好评率100%
很高兴为您提供以下代码:
实体类代码:
```
public class PdfFile {
private Integer id;
private String fileName;
private String filePath;
private Date uploadTime;
private Integer uploaderId;
// getter and setter methods
}
```
控制器代码:
```
@RestController
@RequestMapping("/pdf")
public class PdfController {
@Autowired
private PdfService pdfService;
@PostMapping("/upload")
public String uploadPdf(@RequestParam("file") MultipartFile file, @RequestParam("uploaderId") Integer uploaderId) {
try {
pdfService.savePdf(file, uploaderId);
return "上传成功";
} catch (Exception e) {
e.printStackTrace();
return "上传失败";
}
}
}
```
服务类代码:
```
public interface PdfService {
void savePdf(MultipartFile file, Integer uploaderId) throws Exception;
}
@Service
public class PdfServiceImpl implements PdfService {
@Autowired
private PdfMapper pdfMapper;
@Override
public void savePdf(MultipartFile file, Integer uploaderId) throws Exception {
PdfFile pdfFile = new PdfFile();
pdfFile.setFileName(file.getOriginalFilename());
pdfFile.setUploaderId(uploaderId);
pdfFile.setUploadTime(new Date());
pdfFile.setFilePath("pdf/" + UUID.randomUUID().toString() + ".pdf");
pdfMapper.insert(pdfFile);
File dest = new File(pdfFile.getFilePath());
file.transferTo(dest);
}
}
```
实现类代码:
```
@Mapper
public interface PdfMapper {
void insert(PdfFile pdfFile);
}
@Mapper
public interface UserMapper {
User selectById(Integer id);
}
```
前端代码:
```
<template>
<div>
<el-upload
class="upload-demo"
action="/pdf/upload"
:data="{ uploaderId: uploaderId }"
:on-success="handleSuccess"
:before-upload="beforeUpload"
:show-file-list="false">
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</div>
</template>
<script>
export default {
data() {
return {
uploaderId: 1
}
},
methods: {
beforeUpload(file) {
const isPdf = file.type === 'application/pdf';
if (!isPdf) {
this.$message.error('只能上传 PDF 文件');
}
return isPdf;
},
handleSuccess(response) {
this.$message.success(response);
}
}
}
</script>
```
mybatis代码:
```
<insert id="insert" parameterType="com.example.demo.entity.PdfFile">
insert into pdf_file (file_name, file_path, upload_time, uploader_id)
values (#{fileName}, #{filePath}, #{uploadTime}, #{uploaderId})
</insert>
```
数据库建表语句:
```
CREATE TABLE `pdf_file` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`file_name` varchar(255) NOT NULL,
`file_path` varchar(255) NOT NULL,
`upload_time` datetime NOT NULL,
`uploader_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```
希望这些代码能够帮助到您!
阅读全文