React-Router 4.x Ответ:
В конце концов, мне нравится иметь один объект истории, в котором я могу переносить даже внешние компоненты. Мне нравится делать один файл history.js, который я импортирую по требованию, и просто манипулировать им.
Вам просто нужно изменить
BrowserRouter
на Router и указать поддержку истории. Это ничего не изменяет для вас, кроме того, что у вас есть свой собственный объект истории, который вы можете манипулировать по своему усмотрению.Вам необходимо установить history , библиотеку, используемую
react-router
.Пример использования, нотация ES6:
history.js
import createBrowserHistory from 'history/createBrowserHistory' export default createBrowserHistory()
BasicComponent.js
import React, { Component } from 'react'; import history from './history'; class BasicComponent extends Component { goToIndex(e){ e.preventDefault(); history.push('/'); } render(){ return Previous; } }
] EDIT 16 апреля 2018 года:
Если вам нужно перейти от компонента, который фактически отображается с помощью компонента
Route
, вы также можете получить доступ к истории из реквизита, например:BasicComponent.js
import React, { Component } from 'react'; class BasicComponent extends Component { navigate(e){ e.preventDefault(); this.props.history.push('/url'); } render(){ return Previous; } }
Следующая демонстрация должна помочь решить проблему - потребуется небольшое редактирование используемых каталогов. Здесь есть комментарии, которые должны помочь - в конце концов, они не слишком отличаются от фрагментов кода, которые вы имели. Это было проверено на всех типах изображений, кроме gif, но не предвидит проблем с этим.
<?php
/* Single file upload with resized thumbnail generation */
# The name of the HTML file field
$field='ppic';
# The base directory for uploads
$rootdir=realpath( __DIR__ . '/upload' );
# The directory into which images will be saved
$imagedir=sprintf( '%s/images', $rootdir );
# The directory into which a new thumbnail will be generated
$thumbsdir=sprintf( '%s/images/thumbs', $rootdir );
# For PNG files, the default compression level ( normally 6 )
$compression = 3;
# Set to boolean again later to indicate success/failure
$response = false;
# max image width
$imgwidth=150;
# max file size
$maxsize = pow( 1024, 2 ) * 2; # 2Mb
# allowed file extensions
$extensions=array('jpg','jpeg','png','gif','bmp');
# allowed mimetypes
$mimetypes=array('image/jpeg','image/png','image/gif','image/x-ms-bmp');
if( Следующая демонстрация должна помочь решить проблему - потребуется небольшое редактирование используемых каталогов. Здесь есть комментарии, которые должны помочь - в конце концов, они не слишком отличаются от фрагментов кода, которые вы имели. Это было проверено на всех типах изображений, кроме gif, но не предвидит проблем с этим.
[110]SERVER['REQUEST_METHOD']=='POST' && !empty( Следующая демонстрация должна помочь решить проблему - потребуется небольшое редактирование используемых каталогов. Здесь есть комментарии, которые должны помочь - в конце концов, они не слишком отличаются от фрагментов кода, которые вы имели. Это было проверено на всех типах изображений, кроме gif, но не предвидит проблем с этим.
[110]FILES[ $field ] ) ){
try{
# simple supporting functions
function createdir( $path=null, $perm=0644 ) {
if( !file_exists( $path ) ) {
mkdir( $path, $perm, true );
clearstatcache();
}
}
function getratio( $w=false, $h=false ){
return $w & $h ? $w / $h : false;
}
function getaspect( $w, $h ){
if( $w==$h )return 's';
elseif( $w > $h )return 'l';
elseif( $h > $w )return 'p';
else return 'e';
}
function getsize( $size ){
$units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB' );
$power = $size > 0 ? floor( log( $size, 1024 ) ) : 0;
return number_format( $size / pow( 1024, $power ), 2, '.', ',' ) . ' ' . $units[ $power ];
}
# ensure target directory structure exists
createdir( $imagedir );
createdir( $thumbsdir );
$obj=(object) Следующая демонстрация должна помочь решить проблему - потребуется небольшое редактирование используемых каталогов. Здесь есть комментарии, которые должны помочь - в конце концов, они не слишком отличаются от фрагментов кода, которые вы имели. Это было проверено на всех типах изображений, кроме gif, но не предвидит проблем с этим.
[110]FILES[ $field ];
$name=$obj->name;
$tmp=$obj->tmp_name;
$size=$obj->size;
$type=$obj->type;
$error=$obj->error;
$ext=strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
list( $width, $height, $type, $attr )=getimagesize( $tmp );
$mime=image_type_to_mime_type( $type );
# generate paths for images
$targetfile = $imagedir . DIRECTORY_SEPARATOR . basename( $name );
$thumbnail = $thumbsdir . DIRECTORY_SEPARATOR . basename( $name );
# some basic tests
if( !$error == UPLOAD_ERR_OK ) throw new Exception( sprintf('Upload failed with error code %d', $error ) );
if( !in_array( $ext, $extensions ) ) throw new Exception( sprintf( 'bad file extension (%s)',$ext ) );
if( !in_array( $mime, $mimetypes ) ) throw new Exception( sprintf( 'bad mime type (%s)', $mime) );
if( $width < $imgwidth ) throw new Exception( sprintf('image is too small (%s)', $attr ) );
if( $size > $maxsize ) throw new Exception( sprintf('image is too large ( %s )', getsize( $size ) ) );
# save the uploaded image
if( !is_uploaded_file( $tmp ) ) throw new Exception('file upload attack');
$status = move_uploaded_file( $tmp, $targetfile );
# if the file was saved OK, generate resized thumbnail
if( $status & imagetypes() ){
$ratio = getratio( $width, $height );
$aspect= getaspect( $width, $height );
switch( $aspect ){
case 's':
$thumbwidth = $thumbheight = $imgwidth;
break;
case 'l':
$thumbwidth = $imgwidth;
$thumbheight = $thumbwidth / $ratio;
break;
case 'p':
$thumbheight = $imgwidth;
$thumbwidth = $thumbheight * $ratio;
break;
case 'e':throw new Exception('bad foo');
}
# generate new image
$thumb = imagecreatetruecolor( $thumbwidth, $thumbheight );
# use appropriate methods for the type of file uploaded
switch( $type ){
case IMG_JPG:
$source = @imagecreatefromjpeg( $targetfile );
if( $source ){
@imagecopyresized( $thumb, $source, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height );
@imagejpeg( $thumb,$thumbnail );
}
break;
case IMG_PNG:
case 3:
$source = @imagecreatefrompng( $targetfile );
if( $source ){
@imagecopyresized( $thumb, $source, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height );
@imagepng( $thumb, $thumbnail, $compression );
}
break;
case IMG_GIF:
$source = @imagecreatefromgif( $targetfile );
if( $source ){
@imagecopyresized( $thumb, $source, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height );
@imagegif( $thumb, $thumbnail );
}
break;
case IMG_WBMP && PHP_VERSION_ID > 70200: # available for PHP v7.2+
$source = @imagecreatefrombmp( $targetfile );
if( $source ){
@imagecopyresized( $thumb, $source, 0, 0, 0, 0, $thumbwidth, $thumbheight, $width, $height );
@imagebmp( $thumb, $thumbnail, true );
}
break;
}
# set the success/failure indicator
$response = file_exists( $thumbnail ) && file_exists( $targetfile ) ? true : false;
@imagedestroy( $thumb );
@imagedestroy( $source );
@unlink( $tmp );
clearstatcache();
http_response_code( 200 );
} else {
throw new Exception( 'Failed to save the upoaded image' );
}
}catch( Exception $e ){
/* something's gone wrong again */
$html='
<html>
<head>
<meta charset="utf-8" />
<title>error</title>
<style>
body{display:flex;flex-direction:column;width:100%%;height:100vh;color:red;font-family:cursive;padding:0;margin:0}
h1,a{width:80%%;margin:auto;text-align:center;}
</style>
</head>
<body>
<h1>%s</h1>
<a href="javascript:location.href=location.href" target="_top">Reload</a>
</body>
</html>';
$error=sprintf( 'Error: %s, line: %d', $e->getMessage(), $e->getLine() );
http_response_code( 400 );
exit( sprintf( $html, $error ) );
}
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>combined image upload & resize</title>
<style>
body{display:flex;margin:0;padding:0;height:100vh;font-family:calibri,verdana,arial;}
html,html *{box-sizing:border-box;}
form{display:flex;flex-direction:column;margin:auto;width:80%;height:80vh;align-items:center;padding:1rem;}
form > fieldset{display:flex:flex:1;width:90%;min-width:90%;margin:1rem auto;flex-direction:row;border:1px dashed rgba(100,100,100,0.25);padding:2rem;align-items:center;justify-content:center;}
input{padding:1rem;}
[type='file']{border:1px solid rgba(100,100,100,0.25);padding:0.9rem}
</style>
</head>
<body>
<form method='post' enctype='multipart/form-data'>
<?php
if( Следующая демонстрация должна помочь решить проблему - потребуется небольшое редактирование используемых каталогов. Здесь есть комментарии, которые должны помочь - в конце концов, они не слишком отличаются от фрагментов кода, которые вы имели. Это было проверено на всех типах изображений, кроме gif, но не предвидит проблем с этим.
[110]SERVER['REQUEST_METHOD']=='POST' && !empty( $response ) ){
/*
let user know the uploaded succeeded
... or not
for this demo the upload folder is within the current
working directory thus image paths are relative to this
and not document root.
*/
printf(
'<fieldset>
<h3>%s - File uploaded</h1>
<a href="%s" target="_blank">
<img src="%s" width=%d height=%d title="%s" alt="%s" />
</a>
</fieldset>',
$name,
ltrim( str_replace( array( __DIR__, '\\' ), array('','/'), $targetfile ),'/'),
ltrim( str_replace( array( __DIR__, '\\' ), array('','/'), $thumbnail ),'/'),
$thumbwidth,
$thumbheight,
$name,
$name
);
}
?>
<fieldset>
<input type='file' name='ppic' />
<input type='submit' />
</fieldset>
</form>
</body>
</html>