用Java和vue写批量上传excel文件到sftp的代码,其中要包含controller层,service层,serviceImpl层
时间: 2024-05-09 18:19:21 浏览: 119
Controller层:
```java
@RestController
@RequestMapping("/excel")
public class ExcelController {
@Autowired
private ExcelService excelService;
@PostMapping("/upload")
public ResponseEntity<String> uploadExcel(@RequestParam("file") MultipartFile[] files) {
try {
excelService.uploadExcel(files);
return ResponseEntity.ok("Excel file uploaded successfully.");
} catch (Exception e) {
return ResponseEntity.badRequest().body("Failed to upload Excel file.");
}
}
}
```
Service层:
```java
public interface ExcelService {
void uploadExcel(MultipartFile[] files) throws Exception;
}
@Service
public class ExcelServiceImpl implements ExcelService {
@Value("${sftp.host}")
private String host;
@Value("${sftp.port}")
private int port;
@Value("${sftp.username}")
private String username;
@Value("${sftp.password}")
private String password;
@Value("${sftp.remote.directory}")
private String remoteDirectory;
@Override
public void uploadExcel(MultipartFile[] files) throws Exception {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");
sftp.connect();
for (MultipartFile file : files) {
String fileName = file.getOriginalFilename();
sftp.cd(remoteDirectory);
sftp.put(file.getInputStream(), fileName);
}
sftp.exit();
session.disconnect();
}
}
```
需要在application.properties中添加如下配置:
```
sftp.host=your_sftp_host
sftp.port=your_sftp_port
sftp.username=your_sftp_username
sftp.password=your_sftp_password
sftp.remote.directory=your_sftp_remote_directory
```
Vue页面中使用element-ui的el-upload组件进行文件上传:
```vue
<template>
<el-upload
class="upload-demo"
action="/excel/upload"
:file-list="fileList"
:on-success="handleSuccess"
:on-error="handleError"
:before-upload="beforeUpload"
multiple
drag
>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传excel文件</div>
</el-upload>
</template>
<script>
export default {
data() {
return {
fileList: []
};
},
methods: {
beforeUpload(file) {
const isExcel =
file.type === "application/vnd.ms-excel" ||
file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
if (!isExcel) {
this.$message.error("只能上传excel文件");
}
return isExcel;
},
handleSuccess(response, file, fileList) {
this.$message.success("上传成功");
},
handleError(err, file, fileList) {
this.$message.error("上传失败");
}
}
};
</script>
```
阅读全文