<?php
namespace App\Http\Controllers;
use App\Imports\AdminsoImport;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;
class CompController extends Controller
{
public function uploadsImg(Request $request)
{
if (false==$request->hasFile('photo')) {
return 'errror: is null';
}
$validator = Validator::make($request->file(),[
'photo' => 'file|max:1024|mimes:jpeg,png',
],[
//验证是否为文件
'photo.file' => '请确认文件格式',
//验证文件上传大小
'photo.max' => '最大上传大小为1M',
//验证上传文件格式
'photo.mimes' => '请确认上传为jpg或jpeg的格式图片',
]);
//尺寸验证 dimensions:min_width=100,min_height=100,max_width=1000,max_height=1000
if ($validator->fails()) {//如果有错误
return json_encode(['error'=>$validator->errors()]); //返回得到错误
}else{}
/**
* 第一个参数的路径是在storage/app下面
* store 方法接受相对于文件系统配置的存储文件根目录的路径。这个路径不能包含文件名,因为系统会自动生成唯一的 ID 作为文件名。
* store 方法还接受可选的第二个参数,用于存储文件的磁盘名称。这个方法会返回相对于磁盘根目录的文件路径
*
* 如果你不想自动生成文件名,那么可以使用 storeAs 方法,它接受路径、文件名和磁盘名作为其参数:
*/
//$file=$request->file('photo')->store('');
$file=$request->file('photo')->storeAs('/upload','99999.png');
$path=storage_path('app/upload').$file;
if ($path){
$arr= ['code'=>200,'msg'=>'success','file'=>$path];
}
else{
$arr=['code'=>404,'msg'=>'error','data'=>''];
}
echo json_encode($arr);
}
public function uploadsFile(Request $request)
{
//dump($request->file()->getMimeType());die;
//判断请求中是否存在指定文件
//var_dump($request->hasFile('file'));die;
if (false==$request->hasFile('file')) {
return 'errror: is null';
}
$validator = Validator::make($request->file(),[
'file' => 'file|max:2048',
],[
//验证是否为文件
'file.file' => '请上传你的文件',
//验证文件上传大小
'file.max' => '上传大小为2M',
]);
$csv_mimetypes = array(
'text/csv',
'text/plain',
'application/csv',
'text/comma-separated-values',
'application/excel',
'application/vnd.ms-excel',
'application/vnd.msexcel',
'text/anytext',
'application/octet-stream',
'application/txt',
);
if (false==in_array($request->file('file')->getMimeType(), $csv_mimetypes)) {
return '文件格式不对';
}
if ($validator->fails()) {//如果有错误
//echo 'eeee';die;
echo $validator->errors()->first();die;
//return json_encode(['error'=>$validator->errors()]); //返回得到错误
}else{
//echo 'aaa';die;
}
/**
* 第一个参数的路径是在storage/app下面
* store 方法接受相对于文件系统配置的存储文件根目录的路径。这个路径不能包含文件名,因为系统会自动生成唯一的 ID 作为文件名。
* store 方法还接受可选的第二个参数,用于存储文件的磁盘名称。这个方法会返回相对于磁盘根目录的文件路径
*
* 如果你不想自动生成文件名,那么可以使用 storeAs 方法,它接受路径、文件名和磁盘名作为其参数:
*/
//$file=$request->file('photo')->store('');
$file=$request->file('file')->storeAs('/upload/'.date('Ymd'),rand(10000,99999).'.csv');
//dd($file);
$path=storage_path('app/upload').$file;
if ($path){
$arr= ['code'=>200,'msg'=>'success','file'=>$path];
}
else{
$arr=['code'=>404,'msg'=>'error','data'=>''];
}
echo json_encode($arr);
}
}
laravel8上传测试类
于 2022-02-27 15:59:48 首次发布