刚接触yii2框架,一个ftp上传难了好几天,终于搞定了,
view:
use yii\helpers\Html;
?>
=Html::beginForm("",'post',['enctype' => 'multipart/form-data']);?>
=Html::fileInput('uploadfile','',['id'=>'uploadfile'])?>
=Html::submitButton('提交')?>
=Html::endForm();?>
controller:
if(\yii::$app->request->isPost)
{
if (is_uploaded_file($_FILES['uploadfile']['tmp_name'])) {
$ftp_server = ""; //ftp地址;
$ftp_user_name = ""; //ftp登录名;
$ftp_user_pass = ""; //ftp登录密码;
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
$file = $_FILES['uploadfile']['tmp_name']; //本地路径
$remote_file = '/test/'.$_FILES['uploadfile']['name']; //上传目标地址
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
if (ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
echo "文件:".$_FILES['uploadfile']['name']."上传成功";
} else {
echo "上传失败";
}
ftp_close($conn_id);
}
}
以上是从本地上传文件到ftp指定目录中/test/中,那么问题又来了,如果说根据每个人的工号上传至/test/文件夹下寻找以自己的工号命名的目录中,如果没有这个目录,则新建目录,并上传至其中,有直接上传;当然方法有很多,这只是自己方法,留着以后回头来优化
$a= ftp_nlist($conn_id,"/test/"); //遍历test文件夹
foreach($a as $c)
{
if($c=='/PHP/'.$upaddress)
{
$remote_file = '/PHP/'."$upaddress".'/'.$_FILES['uploadfile']['name'];
echo $remote_file.'
';
if (ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
echo "文件:".$_FILES['uploadfile']['name']."上传成功";
} else {
echo "上传失败";
}
return true;
}
else
{
$bb=@ftp_mkdir($conn_id,"/PHP/"."$upaddress");
$remote_file ="$bb".'/'.$_FILES['uploadfile']['name'];
echo $remote_file.'
';
if (ftp_put($conn_id, $remote_file, $file, FTP_BINARY)) {
echo "文件:".$_FILES['uploadfile']['name']."上传成功";
} else {
echo "上传失败";
}
return true;
}
}