在php中使用csv导入图像

时间:2019-05-29 13:48:29

标签: php laravel

我正在使用php laraval框架创建一个项目。我正在用mysql数据库中的csv文件导入数据。我已成功将数据导入数据库。现在我还想从数据库中的csv上传图像。我在Google上进行了研究,但找不到更好的结果。请帮助解决此问题。 这是代码:

 public function uploadCSV(Request $request){
  $file = $request->file('file');
  $host = $request->root();
  $filename = $file->getClientOriginalName();
  $extension = $file->getClientOriginalExtension();
  $tempPath = $file->getRealPath();
  $fileSize = $file->getSize();
  $mimeType = $file->getMimeType();
  // Valid File Extensions
  $valid_extension = array("csv");
  // 2MB in Bytes
  $maxFileSize = 2097152;

    if(in_array(strtolower($extension),$valid_extension)){
      if($fileSize <= $maxFileSize){
        $pathset = base_path();
        $path = $pathset."/public/uploads/".$_FILES["file"]["name"];
        move_uploaded_file($_FILES["file"]["tmp_name"],$path);
        $location = 'uploads';
        $filepath = public_path($location."/".$filename);
        $file = fopen($filepath,"rn");
        //print_r($file);
        $importData_arr = array();
        $i = 0;
          while (($filedata = fgetcsv($file, 1000, ",")) !== FALSE) {
            $num = count($filedata );
            //Skip first row (Remove below comment if you want to skip the first row)
              if($i == 0){
                $i++;
                continue; 
              }
              for ($c=0; $c < $num; $c++) {
                $importData_arr[$i][] = $filedata [$c];
              }
              $i++;
            }
            fclose($file);
            for($j=1; $j<=count($importData_arr); $j++){
              $eqp =new Equipment();
              $eqp->vendor = $importData_arr[$j][0];
              $eqp->buyerName = $importData_arr[$j][1];
              $eqp->price = $importData_arr[$j][3];
              $eqp->model = $importData_arr[$j][4];
              $eqp->make_year = $importData_arr[$j][5];
              $eqp->image = $importData_arr[$j][6];
              $eqp->save();
              $emailData =new BuyerEmail();
              $emailData->email =  $importData_arr[$j][2];
              $emailData->equipment_id =  $eqp->id;
              $emailData->save();
            }
            return response()->json(['success'=>'success'], 200);
          }
          else{
            return response()->json(['error'=>'Size of file exceeded.'], 200);
          }
        }else{
        return response()->json(['error'=>'File not supported.'], 200);
      }
    }

0 个答案:

没有答案