简体   繁体   中英

How can I check the type of an upload file using Laravel + React?

I am using React + Laravel. For upload file i using Maatwebsite library. I'm just learning, so all this is for a "home project" :) There is a form with an input for selecting a file and a button:

<form>
  <input type="file" name="file" onChange={e => preUploadFile(e)} />
  <Button onClick={importFileHandler} disabled={!file}>Upload</Button>
</form>

I save the selected file to the state:

const [file, setFile] = useState(null);
const preUploadFile = e => {
        const file = e.target.files[0];
        setFile(file);
};

Then I "drop" state into fetch:

// post for import
export const importFileInDataBase = async file => {
    try {
        const formData = new FormData();
        formData.append("file", file);
        await fetch(`${url}/v2/organizations/import`, {
            method: "POST",
            body: formData
        }).then(response => {
            console.log("result", response);
        });
    } catch (error) {
        console.log(error);
    }
};

After that, I call this function by clicking on the button and alsoby clicking on the button I call the function, which will request data from the table with a get request and render it on the page.

const importFileHandler = () => {
    new Promise((resolve, reject) => {
        resolve(importFileInDataBase(file));
    }).then(() => {
        getAllOrganizations();
    });
};

My Model on the back-end:

class ScheduledInspectionModel extends Model
{
    protected $table = 'scheduled_inspection';
    protected $fillable = ['name_smp', 'name_control', "verification_start", "verification_end", 'verification_duration'];
    public $timestamps = false;
}

Controller:

class OrganizationsImportController extends Controller
{
    public function import(Request $request)
    {
        // return dd($request->file);
        Excel::import(new OrganizationsImport, $request->file);
        return response()->json('Success upload');
    }
}

And file with setting for import:

class OrganizationsImport implements ToModel
{
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {
        return new ScheduledInspectionModel([
            'name_smp' => $row[0],
            'name_control' => $row[1],
            'verification_start' => $row[2],
            'verification_end' => $row[3],
            'verification_duration' => $row[4],
        ]);
    }
}

Please tell me how i can\\need to check the type of the imported file (only the .xls file is needed)? PS: another question, I would like to display some message about successful import or not. I in the controller return the message response () -> json ('Import completed'); how can I get use with this? PSS: maybe it comes in handy somehow dd($ response); :

Illuminate\Http\UploadedFile {#282
  -test: false
  -originalName: "test.xls"
  -mimeType: "application/vnd.ms-excel"
  -error: 0
  #hashName: null
  path: "/tmp"
  filename: "phpzFcBzS"
  basename: "phpzFcBzS"
  pathname: "/tmp/phpzFcBzS"
  extension: ""
  realPath: "/tmp/phpzFcBzS"
  aTime: 2020-08-25 14:39:02
  mTime: 2020-08-25 14:39:02
  cTime: 2020-08-25 14:39:02
  inode: 318670
  size: 6144
  perms: 0100600
  owner: 1000
  group: 1000
  type: "file"
  writable: true
  readable: true
  executable: false
  file: true
  dir: false
  link: false
}

You can just use the file input's accept attribute.

<input type="file" name="file" accept=".xls,application/vnd.ms-excel" onChange="..." />

This will only allow you to select .xls files when you click the button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM