当我尝试使用jQuery ajax上传它们时,我无法检测文件的文件类型,
以下是我使用jQuery上传文件的方法:
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]); //my file input
//Header require for the framework I am using
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: window.location.origin+'/'+'dataset/create/'+project.pid,
data:formData,
processData:false,//needs to be false for else jQuery gives illegal invocation
contentType:false,
mimeType:"multipart/form-data",
success: function (data) {
uploadDataCallback(data);
},
error: function (data) {
console.error('Error:', data);
}
});
这是我如何处理我试图找出php中的文件类型,
// Check MIME Type .
$finfo = new finfo(FILEINFO_MIME_TYPE);
//var_dump($finfo->file($_FILES['file']['tmp_name'])); //THIS IS ALWAYS 'text/plain'
if (false === $ext = array_search(
$finfo->file($_FILES['file']['tmp_name']),
array(
'csv' => 'text/csv',
'json' => 'application/json',
'csv' =>'text/plain',
),
true
)) {
throw new Exception('Invalid file format.');
}
$ finfo总是为任何类型的文件提供'text / plain',即csv,json等。我想检测用户上传json文件或csv文件的时间,以便我可以适当地解析它们
以下是整个参考函数:
function create($pid){
$tmpName = $_FILES['file']['tmp_name'];
$file = file($tmpName);
//uploading a file
try {
// Undefined | Multiple Files | $_FILES Corruption Attack
// If this request falls under any of them, treat it invalid.
if(!isset($_FILES['file']) || !is_uploaded_file($_FILES['csv']['tmp_name'][0])){
throw new Exception('File missing');
}
if (
!isset($_FILES['file']['error']) ||
is_array($_FILES['file']['error'])
) {
throw new Exception('Invalid parameters.');
}
// Check $_FILES['file']['error'] value.
switch ($_FILES['file']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
throw new Exception('No file sent.');
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
throw new Exception('Exceeded filesize limit.');
default:
throw new Exception('Unknown errors.');
}
//check filesize here.
if ($_FILES['file']['size'] > 1000000) {
throw new Exception('Exceeded filesize limit.');
}
///////////////THIS IS WHERE IS ALWAYS SAYS 'text/plain' EVEN IF IT IS A JSON FILE
// Check MIME Type .
$finfo = new finfo(FILEINFO_MIME_TYPE);
//var_dump($finfo->file($_FILES['file']['tmp_name'])); //this is always text/plain
if (false === $ext = array_search(
$finfo->file($_FILES['file']['tmp_name']),
array(
'csv' => 'text/csv',
'json' => 'application/json',
'csv' =>'text/plain',
),
true
)) {
throw new Exception('Invalid file format.');
}
// name it uniquely.
// obtain safe unique name from its binary data.
$path=sha1_file($_FILES['file']['tmp_name']);
//dev config
if (!move_uploaded_file(
$_FILES['file']['tmp_name'],
sprintf(base_path().'/public/devStorage/%s.%s',
$path,
$ext
)
)) {
throw new Exception('Failed to move uploaded file.');
}
if($ext=='csv'){
$csvAsArray = array_map('str_getcsv', $file);
//dd($csvAsArray);
$rows=count($csvAsArray);
//everything fine,file is uploaded succesfully
//save dataset
$dataset=new DataSet;
$dataset->name=$_FILES['csv']['name'];
$dataset->iduser=Auth::user()->iduser;
$dataset->pid=$pid;
$dataset->path=$path;
$dataset->type=$ext;
$dataset->rows=$rows;
$dataset->cols=count($csvAsArray[0]);
$dataset->save();
for($i=0;$i<count($csvAsArray[0]);$i++ ){
$datasetCol=new DataSetColumn;
$datasetCol->col_name=$csvAsArray[0][$i]; //first row is assume to be the header row
if(is_numeric($csvAsArray[1][$i])){ //second row is taken as value and its type is assumed for entire column
$datasetCol->col_type='Number';
}
else{
$datasetCol->col_type='String';
}
$datasetCol->iddata_sets=$dataset->iddata_sets;
$datasetCol->save();
}
return json_encode($dataset);
}
else if($ext=='json'){
dd('jsonff');
}
} catch (Exception $e) {
$message='Error:'.$e->getMessage();
return $message;
}
}