【发布时间】:2019-01-24 17:47:38
【问题描述】:
我有一个使用 CroppieJS 的带有裁剪器的小型 symfony 4 应用程序。 当我裁剪并点击保存按钮时,croppie 会向我发送 base64 图像:
$( "#cropSave" ).click(function() {
basic.croppie('result','canvas'
).then(function (result) {}
如何将此结果发送到我的控制器并使用 VichUploader 和 Doctrine 保存图像?
这是我的控制器:
public function updateProfilePicture(Request $request): Response
{
$this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
$user = $this->getUser();
$entityManager = $this->getDoctrine()->getManager();
$user->setImageFile($request->files->get('image'));
$entityManager->flush();
return new Response("ok");
}
我尝试了很多东西,但我一定缺乏经验,因为它不起作用:
var form = document.getElementById("myAwesomeForm");
var ImageURL = result;
// Split the base64 string in data and contentType
var block = ImageURL.split(";");
// Get the content type of the image
var contentType = block[0].split(":")[1];
// get the real base64 content of the file
var realData = block[1].split(",")[1];
// Convert it to a blob to upload
var blob = b64toBlob(realData, contentType);
// Create a FormData and append the file with "image" as parameter name
var formDataToUpload = new FormData(form);
formDataToUpload.append("image", blob);
或
function urltoFile(url, filename, mimeType){
return (fetch(url)
.then(function(res){return res.arrayBuffer();})
.then(function(buf){return new File([buf], filename, {type:mimeType});})
);
}
这是我的 ajax 请求之一:
$.ajax({
type : "POST",
data: formDataToUpload,
url : $('#updateProfilePictureLink').val(),
contentType:false,
processData:false,
cache:false,
dataType:"json",
success : function(response) {
$('#profilePicture').attr('src', result);
alert(response);
},
error : function (response) {
alert("error !");
}
});
我在想也许使用 VichUploader formType 输入字段在 JS 中“模拟”从 base64 上传的文件,但我想知道是否有更简单的方法。
谢谢
【问题讨论】:
-
使用
var img = new Image()然后img.src = 'you b64 string从base64创建图像,然后您发布的数据是img。不知道为什么你会被否决。对我和您尝试使用的方法来说,这似乎是一个很好的问题。永远爱那些投反对票但无话可说的人 -
今晚我正在测试,谢谢
-
实际上你可能不得不将这个图像保留为一个 blob,因为我考虑得更多。您是上传图片还是存储图片的 db 值?
-
croppie 可以直接给我回一个 blob;在
result变量中。我正在使用 vichuploader,他需要为实体分配一个 HTTPFundation/File 类型,然后持久化。他将文件直接链接到用户 -
@Ronnie 你是对的,保留 blob 是正确的做法!
标签: javascript forms symfony base64 symfony4