我不知道您是否找到了解决方案。
用户一选择图片,就可以将图片保存在目录和DB表中的文件名中。
用户选择图片后,使用此小部件2amigon File Upload Widget 开始上传图片。这个小部件呈现jQuery File Upload。
用法:
查看
use dosamigos\fileupload\FileUploadUI;
<?= FileUploadUI::widget([
'model' => $model,
'attribute' => 'profile_pic',
'url' => ['user-profile/upload-profile-picture', 'id' => $model->id],
'gallery' => false,
'fieldOptions' => [
'accept' => 'image/*',
],
'clientOptions' => [
'maxFileSize' => 2000000,
'autoUpload' => true,
],
'clientEvents' => [
'fileuploaddone' => 'function(e, data) {
jQuery(".fb-image-profile").attr("src",data.result);
}',
'fileuploadfail' => 'function(e, data) {
alert("Image Upload Failed, please try again.");
}',
],
]);
?>
Controller :这将调用 UserProfileController/actionUploadProfilePicture 方法。
public function actionUploadProfilePicture($id)
{
$model = $this->findModel($id);
$oldFile = $model->getProfilePictureFile();
$oldProfilePic = $model->profile_pic;
if ($model->load(Yii::$app->request->post())) {
// process uploaded image file instance
$image = $model->uploadProfilePicture();
if($image === false && !empty($oldProfilePic)) {
$model->profile_pic = $oldProfilePic;
}
if ($model->save()) {
// upload only if valid uploaded file instance found
if ($image !== false) { // delete old and overwrite
if(!empty($oldFile) && file_exists($oldFile)) {
unlink($oldFile);
}
$path = $model->getProfilePictureFile();
$image->saveAs($path);
}
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $model->getProfilePictureUrl();
}
}
}
型号
public function getProfilePictureFile()
{
return isset($this->profile_pic) ? Yii::$app->params['uploadPath'] . 'user/profile/' . $this->profile_pic : null;
}
public function getProfilePictureUrl()
{
// return a default image placeholder if your source profile_pic is not found
$profile_pic = isset($this->profile_pic) ? $this->profile_pic : 'default_user.jpg';
return Yii::$app->params['uploadUrl'] . 'user/profile/' . $profile_pic;
}
/**
* Process upload of profile picture
*
* @return mixed the uploaded profile picture instance
*/
public function uploadProfilePicture() {
// get the uploaded file instance. for multiple file uploads
// the following data will return an array (you may need to use
// getInstances method)
$image = UploadedFile::getInstance($this, 'profile_pic');
// if no image was uploaded abort the upload
if (empty($image)) {
return false;
}
// store the source file name
//$this->filename = $image->name;
$ext = end((explode(".", $image->name)));
// generate a unique file name
$this->profile_pic = Yii::$app->security->generateRandomString().".{$ext}";
// the uploaded profile picture instance
return $image;
}
除此之外,您可以使用Advanced upload using Yii2 FileInput widget教程了解更多图片上传的详细信息。
我希望这有助于解决您关于文件上传的问题。