【问题标题】:VichUploader and CroppieJS : how to send a base64 cropped image to persist in Symfony 4VichUploader 和 CroppieJS:如何发送 base64 裁剪图像以保留在 Symfony 4 中
【发布时间】: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


【解决方案1】:

感谢 Ronnie Hint,我设法解决了这个问题。 你必须:

  • 使用JS FormData
  • 把blob放进去
  • 在 Symfony 控制器中将其作为图像检索
  • 按原样保存

但是您必须在图像的实体上实现可序列化(序列化和反序列化所有字段,除非它会破坏您的其他功能)。

这是工作代码示例:

// JS
$( "#cropSave" ).click(function() {
    alert("click !");
    basic.croppie('result','blob'
    ).then(function (result) {
        var fd = new FormData();
        //Third parameter is the blob name
        fd.append('data', 
        result,$('#userId').val()+"."+result.type.split("/")[1]);
            $.ajax({
            type: 'POST',
            url : $('#updateProfilePictureLink').val(),
            data: fd,
            processData: false,
            contentType: false
        }).done(function(data) {
            // your things
        });

// PHP

// Controller
try {
    $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
    $user = $this->getUser();
    $entityManager = $this->getDoctrine()->getManager();
    $user->setImageFile($request->files->get('data'));
    $entityManager->flush();
}
catch (exception $e) {
}

// Entity
class User implements UserInterface, \Serializable
{

/** @see \Serializable::serialize() */
public function serialize()
{
    return serialize(array(
        $this->id,
        $this->profilePicture,
        $this->email,
        $this->password
    ));
}
/** @see \Serializable::unserialize() */
public function unserialize($serialized)
{
    list (
        $this->id,
        $this->profilePicture,
        $this->email,
        $this->password
        ) = unserialize($serialized);
}

【讨论】:

    猜你喜欢
    • 2019-08-03
    • 2016-08-27
    • 2020-02-03
    • 2018-02-15
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多