使用 Ajax 上传 base64 图像 [英] Upload base64 image with Ajax

查看:104
本文介绍了使用 Ajax 上传 base64 图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的客户让用户选择图片、裁剪和调整大小,然后显示它(在 DOM 元素中).
如果图片没问题,用户可以上传到服务器保存.

My client is offering the user to pick a picture, crop and resize it and then display it (in a <img> DOM element).
If the picture is fine, the user can upload it to the server so it can be saved.

由于 Ajax 请求,我想上传.

I would like to do the upload thanks to an Ajax request.

我在互联网上找到了大量示例来上传从客户端 PC 检索到的原始图像.例如:

I found tons of examples on the internet to upload the original image retrieved from the client PC. For instance:

$( '#my-form' )
  .submit( function( e ) {
    $.ajax( {
      url: 'http://host.com/action/',
      type: 'POST',
      data: new FormData( this ),
      processData: false,
      contentType: false
    } );
    e.preventDefault();
  } );

如果我决定上传通过表单输入检索到的图片,这将正常工作.

This works properly if I decide to upload the picture retrieved through the form input.

就我而言,我想上传修改后的图片(保存在 元素中)而不是原始图片.
此图片存储为base64图片(参考:我使用croppie.js库生成图片).

In my case I want to upload the modified picture (saved in a <img> element) instead of the original one.
This picture is stored as a base64 picture (For information: I used the croppie.js library to generate the image).

我不知道如何用 Ajax 上传这张图片.

I don't know how to upload this picture with Ajax.

我尝试将其作为常规参数上传,但在服务器端,img 是空字符串:

I tried to upload it as a regular parameter but on the server side the img is an empty string:

var url = 'http://host.com/action/';
var data = {};
data.img = $('img#generated-image').attr('src');

$.ajax({url: url, type: "POST", data: data})
  .done(function(e){
    // Do something
  });
// RESULTS in a empty data.img on the server side.

我的问题是服务器在检索img"参数时有一个空字符串.我怀疑图像可能太大而无法传递到服务器或其他一些我不明白的问题....

My problem being the server having an empty string when retrieving the "img" parameter. I suspect the image is maybe too big to be passed to the server or some other issues that I don't understand... .

所以我想知道使用 Ajax 请求 WITHOUT 使用表单将 base64 图像发送到服务器的正确方法是什么.

So I'm wondering what is the proper way to send a base64 image to the server using an Ajax request WITHOUT using a form.

感谢您的帮助.

编辑

似乎是 xmlHTTP POST 参数大小问题.我试图减少图像的字符串表示的字符数,服务器现在可以检索它.

Seems to be an xmlHTTP POST parameter size issue. I tried to reduce the number of characters of the string representation of the image and the server is now able to retrieve it.

编辑2

在php.ini文件中post_max_size设置为8M,而图片大小只有24K.所以问题不存在.
我在 Symfony2 框架中使用 PHP.
可能是 Symfony2 的限制.

post_max_size is set to 8M in the php.ini file wheras the picture size is only 24K. So the problem is not there.
I'm using PHP with the Symfony2 framework.
Maybe a limitation from Symfony2.

推荐答案

我最终决定将 base64 图像转换为 Blob,以便它可以通过带有 formData 对象的 Ajax 请求发送,如下所示.它节省了上传带宽(base64 比其二进制等价物多占用 33% 的位)并且我找不到不传输 base64 参数的原因(肯定是由于某处的大小限制).

I finally decided to convert the base64 image to a Blob so it can be sent via an Ajax request with the formData object as follows. It saves upload bandwidth (base64 takes 33% more bits than its binary equivalent) and I couldn't find the reason for no transmission of base64 parameter (due to size limitation somewhere for sure).

base64ToBlob 函数基于另一个问题的答案.

The base64ToBlob function is based on this answer to another question.

function base64ToBlob(base64, mime) 
{
    mime = mime || '';
    var sliceSize = 1024;
    var byteChars = window.atob(base64);
    var byteArrays = [];

    for (var offset = 0, len = byteChars.length; offset < len; offset += sliceSize) {
        var slice = byteChars.slice(offset, offset + sliceSize);

        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }

        var byteArray = new Uint8Array(byteNumbers);

        byteArrays.push(byteArray);
    }

    return new Blob(byteArrays, {type: mime});
}

我的JS代码:

var url = "url/action";                
var image = $('#image-id').attr('src');
var base64ImageContent = image.replace(/^data:image/(png|jpg);base64,/, "");
var blob = base64ToBlob(base64ImageContent, 'image/png');                
var formData = new FormData();
formData.append('picture', blob);

$.ajax({
    url: url, 
    type: "POST", 
    cache: false,
    contentType: false,
    processData: false,
    data: formData})
        .done(function(e){
            alert('done!');
        });

在 Symfony2 中,我可以通过以下方式检索图像:

In Symfony2 I can retrieve the image thanks to:

$picture = $request->files->get('picture');

这篇关于使用 Ajax 上传 base64 图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆