[英]Upload base64 image with Ajax
My client is offering the user to pick a picture, crop and resize it and then display it (in a <img>
DOM element). 我的客户为用户提供了选择图片,裁剪并调整其大小然后显示的信息(在
<img>
DOM元素中)。
If the picture is fine, the user can upload it to the server so it can be saved. 如果图片很好,用户可以将其上传到服务器以便保存。
I would like to do the upload thanks to an Ajax request. 由于Ajax请求,我想上传。
I found tons of examples on the internet to upload the original image retrieved from the client PC. 我在互联网上找到了大量示例,可以上传从客户端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. 如果我决定上载通过表单输入检索的图片,则此方法正常工作。
In my case I want to upload the modified picture (saved in a <img>
element) instead of the original one. 就我而言,我想上传修改后的图片 (保存在
<img>
元素中)而不是原始图片。
This picture is stored as a base64 picture (For information: I used the croppie.js library to generate the image). 此图片存储为base64图片(有关信息:我使用croppie.js库生成了图像)。
I don't know how to upload this picture with Ajax. 我不知道如何用Ajax上传这张照片。
I tried to upload it as a regular parameter but on the server side the img is an empty string: 我试图将其作为常规参数上传,但是在服务器端,img是一个空字符串:
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.
My problem being the server having an empty string when retrieving the "img" parameter. 我的问题是服务器在检索“ img”参数时具有空字符串。 I suspect the image is maybe too big to be passed to the server or some other issues that I don't understand... .
我怀疑图片可能太大而无法传递到服务器或其他我不理解的问题...。
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. 因此,我想知道使用Ajax请求而不使用表单将base64图像发送到服务器的正确方法是什么。
Thanks for your help. 谢谢你的帮助。
EDIT 编辑
Seems to be an xmlHTTP POST parameter size issue. 似乎是xmlHTTP POST参数大小问题。 I tried to reduce the number of characters of the string representation of the image and the server is now able to retrieve it.
我试图减少图像的字符串表示形式的字符数,服务器现在可以检索它。
EDIT2 编辑2
post_max_size is set to 8M in the php.ini file wheras the picture size is only 24K. php.ini文件中的post_max_size设置为8M,而图片大小仅为24K。 So the problem is not there.
因此问题不存在。
I'm using PHP with the Symfony2 framework. 我在Symfony2框架上使用PHP。
Maybe a limitation from Symfony2. 也许是Symfony2的限制。
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. 我最终决定将base64图像转换为Blob,以便可以通过带有formData对象的Ajax请求将其发送,如下所示。 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).
它节省了上传带宽(base64比其二进制等效项多占用33%的位),而且我找不到不传输base64参数的原因(由于一定的大小限制)。
The base64ToBlob function is based on this answer to another question . base64ToBlob函数基于对另一个问题的回答 。
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});
}
My JS code: 我的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!');
});
In Symfony2 I can retrieve the image thanks to: 在Symfony2中,由于以下原因,我可以检索图像:
$picture = $request->files->get('picture');
Nitseg's answer works nicely. Nitseg的答案很好。 Also, I wanted to add the following lines if you must use auth token in your ajax call.
另外,如果您必须在ajax调用中使用auth令牌,我想添加以下几行。 Again, take a look at Nitseg's answer for more details first.
同样,请先查看Nitseg的答案以获取更多详细信息。
var formData = new FormData();
var token = "<YOUR-TOKEN-HERE>";
formData.append("uploadfile", mediaBlob);
jQuery.ajax({
url: url,
type: "POST",
cache: false,
contentType: false,
processData: false,
data: formData,
beforeSend: function (xhr){
xhr.setRequestHeader("Authorization", "Bearer " + token);
}
})
.done((e) => {
// It is done.
})
.fail((e) => {
// Report that there is a problem!
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.