// 数据导入
public function importData()
{
$file = request()->file('file');
$info = $file->validate(['ext' => 'xls,xlsx'])->move(ROOT_PATH . 'public' . DS . 'uploads');
if ($info) {
$filename = $info->getSaveName();
$file_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . $filename;
// 处理导入逻辑
// ...
return json(['code' => 200, 'msg' => '数据导入成功']);
} else {
return json(['code' => 400, 'msg' => $file->getError()]);
}
}
// 数据导出
public function exportData()
{
// 处理导出逻辑
// ...
$filename = 'data_sheet.xlsx';
$file_path = ROOT_PATH . 'public' . DS . 'exports' . DS . $filename;
header("Content-Type: application/vnd.ms-excel");
header("Content-Disposition: attachment;filename=".$filename);
header("Cache-Control: max-age=0");
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
}ThinkPHP实现文件上传和下载功能
// 文件上传
public function uploadFile()
{
$file = request()->file('file');
$info = $file->validate(['ext' => 'jpg,png,gif'])->move(ROOT_PATH . 'public' . DS . 'uploads');
if ($info) {
$filename = $info->getSaveName();
$file_path = ROOT_PATH . 'public' . DS . 'uploads' . DS . $filename;
// 处理上传文件逻辑
// ...
return json(['code' => 200, 'msg' => '文件上传成功']);
} else {
return json(['code' => 400, 'msg' => $file->getError()]);
}
}
// 文件下载
public function downloadFile()
{
// 处理下载逻辑
// ...
$file_path = ROOT_PATH . 'public' . DS . 'downloads' . DS . $filename;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file_path) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
}以上是关于ThinkPHP实现数据导入和导出、以及文件上传和下载功能的代码示例。这些功能在实际的软件开发中经常会用到,希望对您有所帮助。