javascript - upload a file using php script without leaving that page -
i trying upload file in html using php script.
<html> <body> <form id='importpfform' enctype="multipart/form-data" action="http://localhost/js/upload.php" method="post"> <input type="hidden" name="max_file_size" value="1000000" /> choose file upload: <input name="uploaded_file" type="file" /> <input type="submit" value="upload" /> </form> </body> </html> and "upload.php" contains following code:
<?php $upload_key = 'uploaded_file'; if (isset($_files[$upload_key])) { try { $error = $_files[$upload_key]['error']; switch ($error) { case upload_err_ini_size: throw new exception('exceeded upload_max_filesize'); case upload_err_form_size: throw new exception('exceeded max_file_size'); case upload_err_partial: throw new exception('incomplete file uploaded'); case upload_err_no_file: throw new exception('no file uploaded'); case upload_err_no_tmp_dir: throw new exception('no tmp directory'); case upload_err_cant_write: throw new exception('can\'t write data'); case upload_err_extension: throw new exception('extension error'); } $finfo = new finfo(fileinfo_mime); $name = $_files[$upload_key]['name']; $tmp_name = $_files[$upload_key]['tmp_name']; $size = $_files[$upload_key]['size']; if ($size > 350000) throw new exception('exceeded 350kb limit'); if (!is_uploaded_file($tmp_name)) throw new exception('not uploaded file'); $type = $finfo->file($tmp_name); if ($type === false) throw new exception('failed mimetype'); if ($type !== 'text/plain; charset=us-ascii') throw new exception('only csv available'); $new_name = dirname(__file__).'/upload/'.$name; echo $new_name; if (is_file($new_name)) throw new exception("the file {$new_name} exists"); if (!move_uploaded_file($tmp_name,$new_name)) throw new exception('failed move uploaded file'); echo "file uploaded {$new_name}"; } catch (exception $e) { echo 'error: '.$e->getmessage(); } } ?> but method opens new web page. want perform function without leaving web page , need use variable $new_name in html page. modification need perform in html page? i'm pretty sure works via kind of ajax request thing. have no idea i'm talking about. i'm not big on ajax or javascript, function use , i'd learn how works can implement when need , in future.
there 2 choices here. use following code action form , have php in same file.
<?php echo $_server['php_self']; ?> or
header("location: upload.html?new_name=value_of_new_name"); in upload.php successful, in upload.html can use $_get['new_name'] retrieve value of $new_name
Comments
Post a Comment