将图像输出到浏览器,然后再将其保存到文件夹

Output image to browser before saving it to the folder

本文关键字:保存 文件夹 图像 输出 浏览器 然后      更新时间:2023-09-26

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

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

以上所有操作都由 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;
        });

--工作演示--

我在此演示中发表了评论以解释步骤是什么,因此请阅读它们。

如果您不了解此答案中的任何内容,请在下面发表评论,我将更新答案,直到您逐行理解为止。您不会从复制/粘贴中学习,因此请务必了解答案。

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>

我希望这有所帮助。祝您编码愉快!

这可能会

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

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>