1. Common code
/ /...
$file = $request->file('file');
$path = $file->store('public/checks');
/ /...
Copy the code
Error message
- 1. Uploaded
Excel
Files are sometimes packaged automaticallyrar
file - 2. Uploaded
Excel
Files sometimes report errors automatically
"fopen(.. \storage\app\public/checks/vEr8BInHAHwIbxnHUvmEkGlBsaF2z7V8kMfl2Xkd.): failed to open stream: Permission denied"
Copy the code
3. Solution 1
/** * File upload *@param \Illuminate\Http\Request $request
* @return \Illuminate\Http\JsonResponse
*/
public function upload(Request $request)
{
// Set the file suffix whitelist
$allowExt = ["csv"."xls"."xlsx"];
// Set the storage directory
$tmpPath = 'storage/jschecks/' . date('Ym');
$dirPath = public_path($tmpPath);
// If the destination directory cannot be created
if(! is_dir($dirPath) && ! mkdir($dirPath,0777.true)) {
return $this->fail(401.'Upload directory does not have permission to create folder');
}
// If the destination directory does not have write permission
if(is_dir($dirPath) && ! is_writable($dirPath)) {return $this->fail(401.'Upload directory does not have write permission');
}
// Get the file
$file = $request->file('file');
// Verify the file
if(isset($file) && $file->isValid()){
$ext = $file->getClientOriginalExtension(); // Upload file suffix
// Check if it is Excel
if(empty($ext) or in_array(strtolower($ext),$allowExt) === false) {return $this->fail(400.'File types not allowed');
}
// Generate the file name
$fileName = uniqid() . '_' . dechex(microtime(true)).'. '.$ext;
try{
// Store files
$path = $file->move($tmpPath, $fileName);
$webPath = '/' . $path->getPath() . '/' . $fileName;
$data['oldname'] = $file->getClientOriginalName();
$data['newname'] = $fileName;
$data['url'] = url($webPath);
return $this->success_without_index('File import successful! ', $data);
}catch (Exception $ex){
return $this->fail($ex->getCode(), $ex->getMessage()); }}return $this->fail(400.'File verification failed');
}
Copy the code
4. Solution 2
Use with Laravel Medialibrary
/** * File upload *@param Request $request
* @return \Illuminate\Http\JsonResponse
* @throws \Exception
* @throws \Throwable
*/
public function upload(Request $request)
{
// Set the maximum execution time of PHP pages to 30s by default
ini_set('max_execution_time'.300);
// Return information
$data = [];
// Set the file suffix whitelist
$allowExt = ["csv"."xls"."xlsx"];
// Get the file
$file = $request->file('file');
// Simple validation must have a file uploaded
$validator = Validator::make($request->all(), [
'file'= >'required'
]);
// Verify the file suffix
$validator->after(function($validator) use ($file, $allowExt) {
if(! in_array($file->guessClientExtension(), $allowExt)) {return $this->fail(400.'Disallowed file types: Please upload Excel files! '); }});if ($validator->fails()) {
return $this->fail(400.'No valid file found: please upload Excel file! ');
}
$upload = ' ';
DB::transaction(function (a) use ($file, &$data, &$upload) {
// Store file information to database
$upload = Upload::create([
'file_name' => $file->getClientOriginalName(),
'file_ext' => $file->getClientOriginalExtension(),
'category'= >'check',]);// Store to laravel-Medialibrary
$media = $upload->addMediaFromRequest('file')
->toMediaCollection('uploads');
$tmp['filename'] = $media->file_name;
$tmp['url'] = $media->getFullUrl();
$data = $tmp;
});
// Data import
$process = new Process('php '. dirname(app_path()) .'/artisan tqsq2005:excel-import ' . $upload->uuid);
// Run time limit: 60s by default
$process->setTimeout(3600);
// Free time limit
//$process->setIdleTimeout(30);
$process->run();
// Returns the number of inserted data
$upload = $upload->fresh();
$data['inserts'] = $upload->import_records;
if (is_array($data) && $data['inserts'])
return $this->success_without_index('Successful import'.$data['inserts'].'Piece of data! ', $data);
return $this->fail(400.'File import failed');
}
Copy the code