【问题标题】:Ajax upload ImageAjax上传图片
【发布时间】:2015-07-20 19:46:48
【问题描述】:

我正在尝试在文件图像名称更改时使用 ajax 上传图像,但我的代码无法在服务器端获取 $_FILES["InputUploadFileImage"]["tmp_name"];

JQuery 代码

  $('#InputUploadFileImage').change(function() {
        var FilePath = $('#InputUploadFileImage').val();
        var FileSize = this.files[0].size;

        $.ajax({
            type: "POST",
            async: true,
            dataType: "json",
            url: ajaxurl,

            data: ({
                type: "POST",
                action: 'Ajax_ChangingProfileImage',
                FilePath: FilePath,
                FileSize: FileSize
            }),
            success: function (response) {
                if (response.Message === 'ImageSuccessfullyUploaded') {
                    alert('Image Successfully Uploaded.');
                    $('#imgUserImage').image_src = FilePath;
                    console.log(response.FilePath);
                } else {
                    alert('Image was not uploaded successfully.');
                    $('#imgUserImage').image_src = FilePath;
                    console.log(response.FilePath);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(jqXHR);
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
    });

PHP 代码

function Ajax_ChangingProfileImage() {

    $FileTmpPath = $_FILES["InputUploadFileImage"]["tmp_name"];
    $FileSize = $_POST['FileSize'];
    $FilePath = $_SERVER['DOCUMENT_ROOT'] . "restronaut/wp-content/uploads/UsersImages/1.jpg";
    $IsUploaded = move_uploaded_file($FileTmpPath ,$FilePath);

    if ($IsUploaded) {
        $response['Message'] = 'ImageSuccessfullyUploaded';
        $response['FilePath'] = $FilePath;

    } else {
        $response['Message'] = 'ImageNotSuccessfullyUploaded';
        $response['FilePath'] = $FilePath;
    }

    header('Content-Type: application/json');
    echo json_encode($response);
    die();
}

请提供任何帮助,并提前非常感谢..

【问题讨论】:

    标签: javascript php jquery ajax wordpress


    【解决方案1】:

    您需要使用 new formData() 来通过 ajax 调用发送图像。 这相当于设置一个正则形式的enctype(不带ajax)

    有关 formData 对象的更多信息here's a MDN link for you.

    JQuery 代码

    $('#InputUploadFileImage').change(function() {
        /*var FilePath = this.files[0];
        var FileSize = this.files[0].size;
         var file = this.files[0];
        var name = FilePath.name;
        var type = FilePath.type;*/
        var formData = new FormData($('*formId*')[0]);
        $.ajax({
            type: "POST",
            async: true,
            dataType: "json",
            url: ajaxurl,
    
            data: ({
                type: "POST",
                action: 'Ajax_ChangingProfileImage',
                formData : formData 
            }),
            success: function (response) {
                if (response.Message === 'ImageSuccessfullyUploaded') {
                    alert('Image Successfully Uploaded.');
                    $('#imgUserImage').image_src = FilePath;
                    console.log(response.FilePath);
                } else {
                    alert('Image was not uploaded successfully.');
                    $('#imgUserImage').image_src = FilePath;
                    console.log(response.FilePath);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(jqXHR);
                console.log(textStatus);
                console.log(errorThrown);
            }
        });
    });
    

    PHP 代码

    print_r($_FILES);
    

    【讨论】:

    • 你好@Bhavin 我试过这样 var formData = new FormData($('#FormUserInfo')[0]); console.log(formData) 但 formData 返回空
    • @Fadi 您确定您通过[0] 传递的表单节点(由jquery 对象返回)存在吗?
    • @Fadi 你签入 ajax 调用 print_r( $_FILES); 吗?
    【解决方案2】:

    恐怕您无法通过 JavaScript 获取文件上传框的值。因此,您不能像使用标准文本数据一样通过 Ajax 提交文件上传。

    相反,您必须使用 JavaScript 的 FormData 对象将文件包装到 multipart/form-data 发布数据对象中。请参阅此 StackOverflow 问题中接受的答案:

    Upload File With Ajax XmlHttpRequest

    请注意,Internet Explorer 9- 不支持 FormData API。

    【讨论】:

      猜你喜欢
      • 2013-10-27
      • 2012-01-01
      • 1970-01-01
      • 2015-10-30
      • 2023-03-07
      • 1970-01-01
      相关资源
      最近更新 更多