先在后端创建文件上传的实体类uploadfile.java,包括文件名,上传日期,文件路径,上传人编号,然后创建uploadfileController,在其中写一个文件上传的api,然后在vue项目中的api文件夹下写一个uploadfile.js,用axios的方式调用后端的文件上传的api,名为upload_f,然后在vue项目的views文件夹下写一个uploadfile.vue,在uploadfile.vue里调用uploadfile.js中的upload_f实现文件上传
时间: 2023-05-31 10:05:59 浏览: 102
的功能。具体代码如下:
后端uploadfile.java:
```
@Entity
@Table(name = "uploadfile")
public class UploadFile {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "filename")
private String fileName;
@Column(name = "upload_date")
private Date uploadDate;
@Column(name = "file_path")
private String filePath;
@Column(name = "uploader_id")
private Long uploaderId;
// 省略getter和setter方法
}
```
uploadfileController.java:
```
@RestController
@RequestMapping("/api")
public class UploadFileController {
@Autowired
private UploadFileRepository uploadFileRepository;
@PostMapping("/uploadfile")
public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file,
Principal principal) {
UploadFile uploadFile = new UploadFile();
uploadFile.setFileName(file.getOriginalFilename());
uploadFile.setUploadDate(new Date());
uploadFile.setUploaderId(Long.parseLong(principal.getName()));
try {
// 获取文件在服务器上的保存路径
String filePath = "文件上传路径/" + file.getOriginalFilename();
uploadFile.setFilePath(filePath);
// 保存文件到服务器本地
file.transferTo(new File(filePath));
// 将文件信息保存到数据库
uploadFileRepository.save(uploadFile);
return ResponseEntity.ok().build();
} catch (IOException e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
}
```
uploadfile.js:
```
import axios from 'axios';
const BASE_URL = 'http://localhost:8080/api';
export function upload_f(file) {
const formData = new FormData();
formData.append('file', file);
return axios.post(`${BASE_URL}/uploadfile`, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
}
```
uploadfile.vue:
```
<template>
<div>
<input type="file" ref="fileInput" @change="uploadFile" />
</div>
</template>
<script>
import { upload_f } from '@/api/uploadfile';
export default {
name: 'UploadFile',
methods: {
uploadFile() {
const file = this.$refs.fileInput.files[0];
upload_f(file)
.then(() => {
console.log('文件上传成功');
})
.catch(() => {
console.log('文件上传失败');
});
}
}
}
</script>
```
阅读全文