在将图像保存到文件夹之前将图像输出到浏览器

时间:2015-03-10 13:52:34

标签: javascript php jquery ajax codeigniter

我在我的网站上创建了一个功能,用户可以通过上传更改背景图像。程序如下:

用户进入设置页面并选择要上传的图像文件。选择图像后,浏览器将输出它以便用户可以预览 它实际上将它的文件保存到文件夹和文件路径到数据库之前。之后,如果用户对结果感到满意,他可以将其保存到 按“上传背景图像”按钮。

上述所有内容均由AJAX处理。

我很难将图像输出到浏览器而不实际保存两次,先进入tests文件夹,然后再进入背景文件夹。

我正在使用CodeIgniter作为我的后端框架,并使用jQuery来处理我的AJAX请求。

以下是我输出(测试)和保存图片的方法:

public function test_image()
{
    if($this->input->is_ajax_request())
    {

        // This part of code needs to be replaced to only just output the image (return it as a JSON), not actually saving it to another a folder
        $ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
        $new_img_name = random_string('unique'). "." . $ext;

        $config['upload_path'] = './public/images/uploads/tests';
        $config['allowed_types'] = 'gif|jpg|jpeg|png';
        $config['max_size'] = '1000000';
        $config['max_width'] = '2000';
        $config['max_height'] = '1600';
        $config['file_name'] = $new_img_name;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload()) {

            $this->output->set_content_type('application_json');
            $this->output->set_output(json_encode(array('image_errors' => $this->upload->display_errors('<p class="text-center">','</p>'))));
            return false;

        } else {

            $this->output->set_content_type('application_json');
            $this->output->set_output(json_encode(array('userfile' => $new_img_name)));
        }

    } else {

        echo "Not an ajax request";
    }
}

// This method works properly
public function upload_background_image()
{
    if (isset($_POST))
    {
        $ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
        $new_img_name = random_string('unique'). "." . $ext;

        $config['upload_path'] = './public/images/uploads/backgrounds';
        $config['allowed_types'] = 'gif|jpg|jpeg|png';
        $config['max_size'] = '1000000';
        $config['max_width'] = '2000';
        $config['max_height'] = '1600';
        $config['file_name'] = $new_img_name;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload()) {

            $this->output->set_content_type('application_json');
            $this->output->set_output(json_encode(array('image_errors' => $this->upload->display_errors('<p class="text-center">','</p>'))));
            return false;

        } else {

            $this->load->model('user_model');
            $user_id = $this->session->userdata('user_id');

                $upload_photo = $this->user_model->updateUserInfo($user_id, ['body_background_url' => $new_img_name]);

                if ($upload_photo === true) {

                    $this->session->set_userdata(['body_background_url' => $new_img_name]);
                    redirect(base_url());
                }
        }
    }

}

这是我的AJAX:

        $("#bg-cover-file").change(function(e) {
            e.preventDefault();

            var form = $(this).closest('form');

            form.ajaxSubmit({
                dataType: 'json',
                beforeSubmit: function() {
                },
                success: function(response) {
                    if(response.userfile) {

                        // Output the image
                        $('.test-image').attr('src', response.userfile);
                        $('span.file-input').hide();

                        // Change the form action attribute
                        var new_path = 'uploads/upload_background_image';
                        form.attr('action', new_path);

                    } else {
                        $('#error-modal').modal('show');
                        $("#error-body").html(response.image_errors);
                        return false;
                    }
                }
            });
            return false;
        });

3 个答案:

答案 0 :(得分:2)

- 工作演示 -

我在这个演示中添加了注释来解释它们的步骤,请阅读它们。

  

如果你对这个答案一无所知,请在下面留下评论,我会更新答案,直到你理解了行。你没有学习复制/粘贴,所以请务必理解答案。

function MyFunction() {
var img=document.getElementById('BackgroundImage');
var Status=document.getElementById('Status');
var savebtn=document.getElementById('savebtn');
/* SetBG will target the body tag of the web page.
You can change this to any element - 
var SetBG=document.getElementById('YourID').style;
*/
var SetBG=document.body.style;
//Split the image name
var fileExt=img.value.split('.');
//Use the last array from the split and put to lowercase 
var fileformat=fileExt[fileExt.length -1].toLowerCase();
// Check the file extension (Image formats only!)
if((fileformat==='jpg')||(fileformat==='gif')||(fileformat==='png')||(fileformat==='jpeg')) { 			
    if (img.files && img.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
    //----Image is ready for preview.
    SetBG.background='url('+e.target.result+') no-repeat center center fixed';
    /*---- Optional, Set background as cover ---*/
    SetBG.backgroundSize="cover";
	SetBG.OBackgroundSize="cover";
	SetBG.webkitBackgroundSize="cover";
    //--Hide Loading Message
   Status.style.display="none";
   //----- Display (Save/Upload button?)	
   savebtn.style.display="block";
    }

    /*-------Reading File.... 
    	Display a message or loading gif for large images to be processed?
	*/
    Status.innerHTML="Loading...";
	Status.style.display="block";
	savebtn.style.display="none";
    reader.readAsDataURL(img.files[0]);
    }
}else{
/*----User file input not accepted (File isn't jpg/gif/png/jpeg)
Empty the input element and set the background to default.
*/
Status.innerHTML="Format not accepted";
Status.style.display="block";
savebtn.style.display="none";
SetBG.background='white';
document.getElementById('BackgroundImage').value='';
}
}
#Status{display:none;background:white;color:black;font-size:16pt;}
#savebtn{display:none;}
<div id="Status"></div>
<input type="file" id="BackgroundImage" onchange="MyFunction()"/>
<button id="savebtn" onclick="alert('Now upload the image');">Upload and save</button>

我希望这会有所帮助。快乐的编码!

答案 1 :(得分:0)

这可能会帮助你 假设您的浏览器按钮ID为bg-cover-file,并且您想要显示图片的图片代码的ID为preview_image

  $(document).on("change", "#bg-cover-file", function(event)
  {
     if (this.files && this.files[0])
     {
        var reader = new FileReader();

        reader.onload = function (e)
        {
            $('#preview_image').attr('src', e.target.result);
        }

        reader.readAsDataURL(this.files[0]);
     }    
   });

答案 2 :(得分:0)

function MyFunction() {
var img=document.getElementById('BackgroundImage');
var Status=document.getElementById('Status');
var savebtn=document.getElementById('savebtn');
/* SetBG will target the body tag of the web page.
You can change this to any element - 
var SetBG=document.getElementById('YourID').style;
*/
var SetBG=document.body.style;
//Split the image name
var fileExt=img.value.split('.');
//Use the last array from the split and put to lowercase 
var fileformat=fileExt[fileExt.length -1].toLowerCase();
// Check the file extension (Image formats only!)
if((fileformat==='jpg')||(fileformat==='gif')||(fileformat==='png')||(fileformat==='jpeg')) { 			
    if (img.files && img.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
    //----Image is ready for preview.
    SetBG.background='url('+e.target.result+') no-repeat center center fixed';
    /*---- Optional, Set background as cover ---*/
    SetBG.backgroundSize="cover";
	SetBG.OBackgroundSize="cover";
	SetBG.webkitBackgroundSize="cover";
    //--Hide Loading Message
   Status.style.display="none";
   //----- Display (Save/Upload button?)	
   savebtn.style.display="block";
    }

    /*-------Reading File.... 
    	Display a message or loading gif for large images to be processed?
	*/
    Status.innerHTML="Loading...";
	Status.style.display="block";
	savebtn.style.display="none";
    reader.readAsDataURL(img.files[0]);
    }
}else{
/*----User file input not accepted (File isn't jpg/gif/png/jpeg)
Empty the input element and set the background to default.
*/
Status.innerHTML="Format not accepted";
Status.style.display="block";
savebtn.style.display="none";
SetBG.background='white';
document.getElementById('BackgroundImage').value='';
}
}
#Status{display:none;background:white;color:black;font-size:16pt;}
#savebtn{display:none;}
<div id="Status"></div>
<input type="file" id="BackgroundImage" onchange="MyFunction()"/>
<button id="savebtn" onclick="alert('Now upload the image');">Upload and save</button>