【问题标题】:File upload through AJAX call, it's possible or not? I'm confused通过AJAX调用上传文件,可以吗?我糊涂了
【发布时间】:2014-11-15 07:20:45
【问题描述】:

我正在开发一个应用程序,我通过序列化表单从表单发送数据,然后通过 AJAX 发送数据。一切都很完美,但我第一个头疼的是,当表单有一个FILE 类型的字段用于将任何类型的文件(应该仅限于图像,但这是另一个主题)上传到我的服务器端(Symfony2控制器操作)代码没有获取图像字段,因此无法对其执行任何操作。

我做了一些研究(1,2,3,4 以及在 Google 上找到的更多文档),在某些情况下据说这是可能的,在某些情况下说是不,其他人使用XHR object,然后我很困惑,不知道从这里去哪里,在这里我留下我的代码让他看看,告诉我出了什么问题,如果可能的话我应该怎么做才能上传(我认为是):

$.ajax({
    async: false,
    type: "POST",
    cache: false,
    url: '{{ path('update-product', {'id': id}) }}',
    data: $('.smart-form').serializeArray(),
    success: function (data) {
        // here goes a message if all was fine
    }
});

这是 HTML 字段:

<input type="file" id="product_imageFile_file" name="product[imageFile][file]" class="valid">

当然我的表单有enctype="multipart/form-data",这是我从 Symfony2 控制器操作中得到的请求:

array(4)
   [product_name]: string (10) "Producto-1"
   [active]: string (1) "1"
   [product_description]: string (21) "DescripcionProducto-1"
   [_token]: string (43) "sjcpVT34_9-V7Z2doTZsvZsAewO-0Q5hD-a9C6VPNc4"

正如这里所见,请求中没有product[imageFile][file],所以我的 jQuery 代码有问题,谁能给我一些帮助或指出我正确的地方吗?

注意:由于我使用 PHP 和其中的一些捆绑包来处理文件上传,然后管理实体,我不知道使用数千个中的任何一个是否是一个好习惯jQuery插件可以做到这一点,这就是我在这里没有提到的原因,我根本不使用它们

提前致谢

【问题讨论】:

  • 是的,这是可能的,但您不会以您的方式看到文件。谷歌 dropzone ajax 上传。该插件对我来说很好用。
  • 大量的 jQuery 插件可以做到这一点。
  • @Popnoodles 看看我在主帖中给李·泰勒留下的留言
  • @ReynierPM 我不明白那句话。重申一下,您不会在 ajax 发布的表单数据中找到该文件。选择一个插件并完整阅读说明。
  • 使用 FormData() 和 ajax 给 PHP 它通常的 $_FILES,或者捕获 POST 数据并自己处理。

标签: javascript php jquery ajax file-upload


【解决方案1】:

好吧,最后,经过大量研究,我得到了它,并且没有任何外部库,正如一些用户在这里建议的那样,也许这是一种丑陋的方法,但它对我有用,并且可以满足我的需求。代码如下:

function handleFileSelect(evt) {
    var files = evt.target.files; // FileList object

    // Loop through the FileList and render image files as thumbnails.
    for (var i = 0, f; f = files[i]; i++) {
        // Only process image files.
        if (!f.type.match('image.*')) {
            // Display some alert or show the user the file is wrong
            continue;
        }

        var reader = new FileReader();

        // Closure to capture the file information.
        reader.onload = (function (theFile) {
            return function (e) {
                // Render thumbnail.
                var span = document.createElement('span');
                span.innerHTML = ['<img id="product_image" class="thumb" src="', e.target.result, '" title="', escape(theFile.name), '"/>'].join('');
                document.getElementById('pImage').insertBefore(span, null);
            };
        })(f);

        // Read in the image file as a data URL.
        reader.readAsDataURL(f);
    }
}

document.getElementById('imageFile_file').addEventListener('change', handleFileSelect, false);

$.ajax({
    async: false,
    url: url, // the URL for process the whole form
    type: 'POST',
    data: $('#formID').serialize() + '&img=' + JSON.stringify($("#product_image").attr('src')),
    cache: false,
    success: function (data)
    {
        if (typeof data.error === 'undefined')
        {
            // Handle success here
        }
        else
        {
            // Handle errors here
        }
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
    },
    complete: function ()
    {
        // STOP LOADING SPINNER
    }
});

希望能帮助别人

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 2011-08-11
    相关资源
    最近更新 更多