【发布时间】:2015-03-19 17:38:01
【问题描述】:
我正在使用 imgly 图像裁剪器插件,针对我的应用做了一些修改。它目前将图像转换为dataUrl 并将图像吐出为base64 图像,我可以将其保存为jpeg。我正在努力将here 中的dataURItoBlob 函数改编为我的应用程序,以便将图像发布到 API 端点。到目前为止,我有以下内容,但我不确定如何将最终图像附加到xhr.open('POST', '/', true);
renderButton.click(function (event) {
var dataUrl =
imgly.renderToDataURL("image/jpeg", { size: "1200" }, function (err, dataUrl) {
//Convert DataURL to Blob to send over Ajax
function dataURItoBlob(dataUrl) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataUrl.split(',')[1]);
// separate out the mime component
var mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
//var bb = new BlobBuilder();
//bb.append(ab);
//return bb.getBlob(mimeString);
}
var blob = dataURItoBlob(dataUrl);
var fd = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
fd.append("myFile", blob);
xhr.open('POST', '/', true);
xhr.send(fd);
//Appends generated dataUrl to a div
var image = $("<img><br>").attr({
src: dataUrl
});
//Remove button
image.appendTo($(".result"))
$button = $('<button class="btn btn-default remove">')
.text('Remove Image')
.on('click', function () {
image.remove();
$(this).remove();
return false;
});
$button.appendTo($(".result"));
});
});
});
【问题讨论】:
-
我用`dataURLToBlob: function(dataURL)`切换更新了函数,但它不允许加载图像,并在单击渲染按钮之前显示结果div。我用所有使用的 js 创建了一个小提琴:jsfiddle.net/Lgduvce1
-
html?在“框架和扩展”jsfiddle.net/Lgduvce1/1 加载 jquery -
我已经用所有的 JS 和 UI 更新了小提琴:jsfiddle.net/mattography/Lgduvce1/2
标签: javascript jquery ajax xmlhttprequest data-uri