从blob创建文件 [英] Creating a file from a blob
问题描述
我需要一些javascript大师。我有这段代码:
I'm in need of some javascript guru. I have this code:
handleImage(new File([blob], blob.name, {type: blob.type})).done(/* something */)
和
handleImage = function (image) {
// create some fake form data
var formData = new FormData();
formData.append("attachment", image);
formData.append("auto", true);
formData.append("_csrf", "xxxxxxxxx");
// post to the server.
return $.ajax({
url: "/some/url",
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
error: function () {
console.log("error");
}
});
这适用于Chrome和Firefox,但在使用Safari(10.1.1)时,服务器( java / spring mvc)在 MultipartHttpServletRequest
中接收附件的空文件。所以在我看来,新文件([blob],blob.name,{type:blob.type})
在某种程度上失败了。
This works fine with Chrome and Firefox, but when using Safari (10.1.1), the server (java / spring mvc) receive in the MultipartHttpServletRequest
an empty file for "attachment". So it seems to me that new File([blob], blob.name, {type: blob.type})
is somehow failing.
这里有什么问题吗?
推荐答案
这可能是safari的年轻实现中的一个错误。
This is probably a bug in safari's young implementation.
但为什么你甚至将它转换为File对象?
一个文件对象是一个Blob,唯一的区别是它有一个名称
和一个 lastModified
属性。但是因为你似乎已经扩展了你的 blob
,所以它只留下你可以添加的 lastModified
属性。
A File object is a Blob, the only difference being that it has a name
and a lastModified
properties. But since you already seem to extend your blob
, it leaves only this lastModified
property that you could add too anyway.
我能想到的唯一一个API,如果你的对象是Blob或文件,它会有所不同 FormData.append
方法;如果您传递File对象,它将能够自动设置文件名。但是此方法有第三个参数,允许您设置此文件名。
The only API I can think of, where it makes a difference if your object is a Blob or a File is FormData.append
method ; where if you pass a File object, it will be able to set the filename automatically. But this method has a third parameter, allowing you to set this filename.
因此,如果您将代码更改为包含 formData.append(attachment ,image,image.name);
并直接用 handleImage(blob)
调用它,它会完成与你的请求完全相同的请求我正在做,除了它可以在Safari和其他所有不支持File构造函数的浏览器上工作(看着你的IE)。
So if you change your code to include formData.append("attachment", image, image.name);
and call it with handleImage(blob)
directly, it will do exactly the same request as the one you're doing, except that it will work on Safari and every other browser that don't support the File constructor (looking at you IE).
这篇关于从blob创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!