通过 ajax 和 php 上传图像文件

upload image file through ajax and php

我不熟悉我面临的这个问题。我想通过 ajax & php

上传图像文件

到目前为止我已经做了这些: HTML:

<input type="file" name="file" id="file" class="inputfile">
<label for="file">Choose a file</label>

ajax:

jQuery(document).ready(function($) {
var data = {

                business_name: $('#business_name').val(),
                business_country: $('#business-country').val(),
                business_region: $('#business-region').val(),
                business_phone: $('#business_phone').val(),
                //business_image: $('#image-data').val(),
                business_image: $('#file').val(),
                token: $('#token').val()
            }
$.ajax({
                type: "POST",
                data: data,
                url: "index.php?route=account/profile/savetoken=" + data.token,
            success: function(data) {
                $("#containerAlertMessages").html("<div id='alertMessages' class='alert alert-success'><strong>Success!</strong> Your profile has been successfully saved!</div>");
                }
            });    
});

我可以获取图片的路径名并将其存储到数据库..但是我无法将图片上传到特定文件夹..

我正在使用像 openCart 这样的 MVC 模型。实际上我得到了 OC 的结构,并从中构建了一个仪表板。

有没有办法使用 OC 已有的工具,例如:

$this->load->model('tool/image');

不然怎么上传图片呢? 序列化表格之类的?

请尽可能具体,以便我理解!

提前致谢!

好的,我解决了 issue/error 关于我自己的问题。我实际上了解了很多关于 openCart 如何上传图片、ajax 和 xhr 如何工作等等。不管怎样,我用过的代码是这样的:

内部文件 profile.tpl:

$('#upload-image').on('click',function(e){
    var formData = new FormData($('#submitProfile')[0]);
    formData.append('route','account/profile');
    $.ajax({
        url: 'index.php?route=tool/upload/logo',
        type: 'post',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        beforeSend: function() {
          $("#containerAlertMessages").html("<div class='alert alert-info'><strong>Sending...</strong></div>");
                    $("#containerAlertMessages").removeClass("containerAlertMessages").addClass("containerAlertMessagesVisible");
        },
        complete: function() {
            $("#containerAlertMessages").html("<div id='alertMessages' class='alert alert-success'><strong>Success!</strong> Your logo has been uploaded successfully! Do not forget to save the abovr information by clicking the Save button at the bottom right corner!</div>");
            $("#containerAlertMessages").removeClass("containerAlertMessages").addClass("containerAlertMessagesVisible");
        },
        success: function() {
            //nothing yet
        },
        error: function(xhr, ajaxOptions, thrownError) {
          alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
      });
    });

内部文件 upload.php:

public function logo() {
        $this->load->language('tool/upload');

        if (!empty($this->request->files['file']['name']) && is_file($this->request->files['file']['tmp_name'])) {
            $filename = html_entity_decode($this->request->files['file']['name'], ENT_QUOTES, 'UTF-8');


            $route = $this->request->post['route'];
            if($route == "account/profile") {
                $file = "image/" . $filename;
                move_uploaded_file($this->request->files['file']['tmp_name'], DIR_LOGOS . $file);
            }
        }
    }
  • DIR_LOGOS 已在 config.php 文件 中定义,因此如果需要,我可以在另一个文件中再次引用此变量。
  • 此外,我正在发送路由变量,以便了解图像上传的来源。 因此,如果上传来自 'account/profile',我会将图像保存到“/image”文件夹 如果它来自 'accoun/register',我将保存到“/image/register”或我想要的任何文件夹(现有或不存在),依此类推

希望对遇到同样问题的人有所帮助!

我用这个代码

index.php

if (!empty($this->request->files)) {
    foreach ($this->request->files as $key => $file) {
        if (!empty($file['name']) && is_file($file['tmp_name'])) {
            $filename = date('YmdHis') . rand(0,10000) . html_entity_decode($file['name'], ENT_QUOTES, 'UTF-8');
            move_uploaded_file($file['tmp_name'], "image/".$filename);
        }
    }
}

main.js

$('#pForm').on('submit',function (e) {
    e.preventDefault();

    $.post({
        url: 'index.php?route=ajax/index',
        data: new FormData(this),
        cache:false,
        contentType: false,
        processData: false,
        success: function () {
            //To do something
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
    });
})