将图像保存到临时文件夹中,然后在提交后将其保存到文件夹cakephp
问题描述:
我试图先将图片保存到临时文件夹,一旦用户从文件选项中选择它。然后在提交表单后保存它以移动文件夹。将图像保存到临时文件夹中,然后在提交后将其保存到文件夹cakephp
这里是上传代码:
$id = $this->Session->read('Auth.User.id');
$userData = $this->User->findById($id);
if ($userData['User']['id'] === $this->Session->read('Auth.User.id')) {
$this->set('userData', $userData);
} else {
throw new NotFoundException(__('You are not allowed to this page!'));
}
move_uploaded_file($fileTmp, WWW_ROOT.'files\Users'.DS.$uid.DS.$fileInfo['tmpFileName']);
此代码让我直接将其保存到文件夹,而不将其保存到临时文件夹。
我想保存正在预览的内容。
这是我在预览的javascript:
//preview
$("#file").change(function() {
var file = this.files[0];
var imagefile = file.type;
var imagesize = file.size;
var match= ["image/jpeg","image/png","image/jpg","image/gif"];
$('.upload-submit').prop('disabled',false).css('opacity',1);
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2]) || (imagefile==match[3])))
{
$("#message").html("<p id='error' style='color:red;'>Please Select A valid Image File</p>"+"<h4 style='color:red;'>Note</h4>"+"<span id='error_message' style='color:red;'>Only jpeg, jpg, gif and png Images type allowed</span>");
return false;
} else if (imagesize > 6000000){
$("#message").html("<p id='error' style='color:red;'>Your file size is higher than the allowed size (6MB)</p>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
var imgData = reader.onload; }
});
function imageIsLoaded(e) {
$("#file").css("color","green");
$('#image_preview').css("display", "block");
$('#previewing').attr('src', e.target.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
};
和我的HTML:
<form method="post" action="https://stackoverflow.com/users/profileimg_edit" enctype="multipart/form-data" id="uploadimage">
<?php echo $this->Session->flash(); ?>
<input type="file" name="file" id="file" class="upload-image-btn" >
<div id="image_preview"><img id="previewing" src="/images/noimage.png" width="80" height="80" />
<div id="message"></div>
</div>
<button class="upload-submit"> Upload Image </button>
</form>
有了这个代码,那他/她选择的用户可以查看和保存它,但我想要的是将其首先保存在临时文件夹中。
谢谢你的帮助,将给予。
答
首先将图片移动到服务器上的临时目录(例如,WWW_ROOT . 'tmp' . DS . $fileInfo['tmpFileName']
),然后在预览中使用该路径(以使URL变得类似于http://my.server.com/tmp/b5c8f033dfaa.jpg
)。然后,当用户完成预览时,将文件移至最终目的地。
但是,您必须跟踪临时文件名($fileInfo['tmpFileName']
),因为如果转到下一页,该信息将丢失。您可以将其放入URL中或将其存储在Session对象中。
你也可能要添加的cronjob从tmp
目录中删除旧的上载文件,因为通常会有一些abandonded文件上传等
“这个代码让我直接保存到文件夹而不保存它到临时文件夹“。和“使用此代码,用户可以查看他/她选择并保存的内容,但我想先将其保存在临时文件夹中。” ??? – Salines