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

Output image to browser before saving it to the folder

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

用户进入设置页面并选择要上传的图像文件。选择图片后,浏览器会输出图片供用户预览 在实际将其文件保存到数据库中的文件夹和文件路径之前。之后,如果用户对结果满意,他可以将其保存到 按 "Upload Background Image" 按钮创建文件夹。

以上都是用AJAX处理的。

我无法将图像输出到浏览器,而没有实际保存两次,第一次保存到测试文件夹,然后保存到背景文件夹。

我使用 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;
        });

这可能对您有所帮助
假设您的浏览按钮的 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]);
     }    
   });

--工作演示--

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

If you don't understand anything in this answer please leave a comment below and i will update the answer until you understand line for line. You don't learn from copy/paste so please be sure to understand the answer.

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>

希望对您有所帮助。编码愉快!

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>