javascript 如何使用dropzone上传base64图像资源?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22785576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:46:14  来源:igfitidea点击:

How to upload base64 image resource with dropzone?

javascriptjquerysymfonyfile-uploaddropzone.js

提问by ArGh

I'm trying to upload generated client side documents (images for the moment) with Dropzone.js.

我正在尝试使用Dropzone.js上传生成的客户端文档(目前为图像)。

// .../init.js

var myDropzone = new Dropzone("form.dropzone", {
    autoProcessQueue: true
}); 

Once the client have finished his job, he just have to click a save button which call the save function :

一旦客户完成了他的工作,他只需要点击一个调用保存函数的保存按钮:

// .../save.js

function save(myDocument) {

    var file = { 
        name: 'Test',
        src: myDocument,
    };

    console.log(myDocument);

    myDropzone.addFile(file);
}

The console.log() correctly return me the content of my document

console.log() 正确返回我的文档内容

 data:image/png;base64,iVBORw0KGgoAAAANS...

At this point, we can see the progress bar uploading the document in the drop zone but the upload failed.

此时,我们可以在拖放区看到上传文档的进度条,但上传失败。

Here is my (standart dropzone) HTML form :

这是我的(标准 dropzone)HTML 表单:

<form action="/upload" enctype="multipart/form-data" method="post" class="dropzone">
    <div class="dz-default dz-message"><span>Drop files here to upload</span></div>
    <div class="fallback">
        <input name="file" type="file" />
    </div>
</form>

I got a Symfony2 controller who receive the post request.

我有一个接收发布请求的 Symfony2 控制器。

// Get request
$request = $this->get('request'); 

// Get files
$files = $request->files;

// Upload
$do = $service->upload($files);

Uploading from the dropzone (by drag and drop or click) is working and the uploads are successfull but using the myDropzone.addFile() function return me an empty object in my controller :

从放置区上传(通过拖放或单击)正在工作并且上传成功,但使用 myDropzone.addFile() 函数在我的控制器中返回一个空对象:

var_dump($files);

return

返回

object(Symfony\Component\HttpFoundation\FileBag)#11 (1) {
  ["parameters":protected]=>
  array(0) {
  }
}

I think i don't setup correctly my var file in the save function. I tryied to create JS image (var img = new Image() ...) but without any success.

我想我没有在保存功能中正确设置我的 var 文件。我尝试创建 JS 图像(var img = new Image() ...)但没有任何成功。

Thanks for your help !

谢谢你的帮助 !

回答by ArGh

Finally i found a working solution without creating canvas :

最后我找到了一个没有创建画布的工作解决方案:

function dataURItoBlob(dataURI) {
    'use strict'
    var byteString, 
        mimestring 

    if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
        byteString = atob(dataURI.split(',')[1])
    } else {
        byteString = decodeURI(dataURI.split(',')[1])
    }

    mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]

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

    return new Blob([new Uint8Array(content)], {type: mimestring});
}

And the save function :

和保存功能:

function save(dataURI) {

    var blob = dataURItoBlob(dataURI);
    myDropzone.addFile(blob);

}

The file appears correctly in dropzone and is successfully uploaded. I still have to work on the filename (my document is named "blob").

该文件在 dropzone 中正确显示并成功上传。我仍然需要处理文件名(我的文档名为“blob”)。

The dataURItoBlob function have been found here : Convert Data URI to File then append to FormData

在这里找到了 dataURItoBlob 函数:Convert Data URI to File then append to FormData

[EDIT]: I finally wrote the function in dropzone to do this job. You can check it here : https://github.com/CasperArGh/dropzoneAnd you can use it like this :

[编辑]:我终于在 dropzone 中编写了这个函数来完成这项工作。你可以在这里查看:https: //github.com/CasperArGh/dropzone你可以像这样使用它:

var dataURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmAAAAKwCAYAAA...';
myDropzone.addBlob(dataURI, 'test.png');

回答by Cayce K

I can't comment currently and wanted to send this to you.

我目前无法发表评论,想把这个发给你。

I know you found your answer, but I had some trouble using your Git code and reshaped it a little for my needs, but I am about 100% positive this will work for EVERY possible need to add a file or a blob or anything and be able to apply a name to it.

我知道你找到了你的答案,但我在使用你的 Git 代码时遇到了一些麻烦,并根据我的需要对它进行了一些改造,但我大约 100% 肯定这将适用于所有可能需要添加文件或 blob 或任何东西的情况能够对其应用名称。

Dropzone.prototype.addFileName = function(file, name) {
    file.name = name;
  file.upload = {
    progress: 0,
    total: file.size,
    bytesSent: 0
  };
  this.files.push(file);
  file.status = Dropzone.ADDED;
  this.emit("addedfile", file);
  this._enqueueThumbnail(file);
  return this.accept(file, (function(_this) {
    return function(error) {
      if (error) {
        file.accepted = false;
        _this._errorProcessing([file], error);
      } else {
        file.accepted = true;
        if (_this.options.autoQueue) {
          _this.enqueueFile(file);
        }
      }
      return _this._updateMaxFilesReachedClass();
    };
  })(this));
};

If this is added to dropzone.js (I did just below the line with Dropzone.prototype.addFile = function(file) {potentially line 1110.

如果将其添加到 dropzone.js(我在Dropzone.prototype.addFile = function(file) {可能为 line的行下方进行了操作)1110

Works like a charm and used just the same as any other. myDropzone.addFileName(file,name)!

就像魅力一样,使用起来与其他任何东西一样。myDropzone.addFileName(file,name)

Hopefully someone finds this useful and doesn't need to recreate it!

希望有人发现这很有用并且不需要重新创建它!

回答by Jens A. Koch

1) You say that: "Once the client have finished his job, he just have to click a save button which call the save function:"

1)你说:“一旦客户完成了他的工作,他只需要点击一个调用保存函数的保存按钮:”

This implies that you set autoProcessQueue: falseand intercept the button click, to execute the saveFile() function.

这意味着您设置autoProcessQueue: false并拦截按钮单击,以执行 saveFile() 函数。

$("#submitButton").click(function(e) {
    // let the event not bubble up
    e.preventDefault();
    e.stopPropagation();
    // process the uploads
    myDropzone.processQueue();
});

2) check form action

2)检查表单动作

Check that your form action="/upload"is routed correctly to your SF controller & action.

检查您的表单action="/upload"是否正确路由到您的 SF 控制器和操作。

3) Example Code

3) 示例代码

You may find a full example over at the official Wiki

您可以在官方Wiki 上找到完整的示例

4) Ok, thanks to your comments, i understood the question better:

4)好的,感谢您的评论,我更好地理解了这个问题:

"How can i save my base64 image resource with dropzone?"

“如何使用 dropzone 保存我的 base64 图像资源?”

You need to embedd the image content as value

您需要将图像内容作为值嵌入

// base64 data
var dataURL = canvas.toDataURL();

// insert the data into the form
document.getElementById('image').value = canvas.toDataURL('image/png');
//or jQ: $('#img').val(canvas.toDataURL("image/png"));

// trigger submit of the form
document.forms["form1"].submit();