将blob(image)传递给php/lavel并获取输入和保存
Passing blob(image) to php/laravel and getting input and saving
用户选择带有文件的img。然后,我用所选文件中的数据img动态创建一个表单。并将其作为标记的源。稍后,当用户按下submit时,我会创建一个FormData对象。并从DataUri获取blob。
这是用于查找正确img的代码,它可以有多个img。
var images = [];
$('#imgDiv'+id+' img').each(function(index, img){
images[index] = dataURItoBlob(img.src);
});
和dataURItoBlob函数
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: 'image/*'});
}
然后我将img附加到formData。
formData.append('images[]',images);
做这个
var req = new XMLHttpRequest();
req.open('post','/ads/add');
req.send(formData);
和php端。使用laravel我试过这个
$images = Input::file('images[]');
为我返回null。相同
$images = Input::file('images');
当我尝试这个时
$images = Input::get('images');
它以json响应["[object Blob]"]的形式返回或者作为dd()返回
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=1)</i>
0 <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'[object Blob]'</font> <i>(length=13)</i>
</pre>
然后我如何将其保存在例如/uploads/images/1
是否需要将数据url转换为blob?
如果没有,您可以通过在ajax请求中发送图像的数据uri(base64)来上传图像,并在php端对其进行解码
供参考:http://www.codepool.biz/tech-frontier/html5/upload-html-canvas-data-to-php-server.html
我和你一样遇到了同样的麻烦。我解决了。
您试图使用Array和formData进行传输。像这个
formData.append('images[]',[object1, object2, objec3, ...]);
然而,这是错误的。如果我们想传输很多文件,我们应该这样编码。
$('#imgDiv'+id+' img').each(function(index, img){
images[index] = img.src;
});
和
for(i=0; i<images.length; i++){
var blob = dataURLtoBlob(images[index]);
formData.append("images[]", blob); // we must use "append" many time.
}
相关文章:
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- jquery试图按名称获取按钮位置
- 如何在jQuery中获取元素的形式
- 如何在php文件中获取$.post-ajax传递的值
- 在Shopify中获取博客文章的图片
- 使用Javascript获取所选选项ID
- 在jQuery中获取表的行索引
- 使用jquery将mysql数据获取到新的表行中
- 在动态创建的元素上获取对特定选择器的引用
- 从城市名称获取惊喜
- Angular只从数组中获取所需的数据
- 无法将数据从firebase获取到我的html页面
- 从ajax请求中获取javascript对象
- 如何从画布上的某个移动事件中获取X和Y
- 是否有一个JS/jQuery函数可以获取某个类的每个元素的ID
- 如何在PHP中使用$_POST获取Select元素值
- 获取@ResponseBody的一部分作为主干和Spring MVC控制器之间的参数
- 从Rally获取一个特定的标记,以便计算另一个字段中的值
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 将blob(image)传递给php/lavel并获取输入和保存