简体   繁体   English

使用html5将数据上传到服务器时,是否可以在blob数据中设置文件名?

[英]Can I set file name in blob data when I upload data to server using html5?

I use event.clipboardData to get image from clipboard, and then upload it server, code: 我使用event.clipboardData从剪贴板获取图像,然后上传服务器,代码:

var items = e.clipboardData.items;
for(var i=0;i<items.length;i++)
{
    if(items[i].type.indexOf("image")!=-1)
    {
        var blob=items[i].getAsFile();
        var data = new FormData();
        data.append("ImageFileField",blob);
        _post2("url...",data);
    }
}

NOTE: _post2() is a function using XMLHttpRequest to do upload works. 注意: _post2()是一个使用XMLHttpRequest进行上传工作的函数。

Above code work fine, the image from clipboard can upload to my server directly. 上面的代码工作正常,剪贴板中的图像可以直接上传到我的服务器。

BUT I found a problem, the filename of image upload to server is fixed as "blob", can I modify the filename before upload to server? 但我发现问题,图像上传到服务器的文件名固定为“blob”,我可以在上传到服务器之前修改文件名吗?

This is the upload data detail: 这是上传数据的详细信息:

Request Payload 请求有效负载

------WebKitFormBoundaryW0NQVOkdrfkYGWV3 ------ WebKitFormBoundaryW0NQVOkdrfkYGWV3
Content-Disposition: form-data; 内容处理:表格数据; name="%%File.48257279001171c9.2c36671da7f1b6c9482575de002e1f14.$Body.0.3D8"; NAME = “%% File.48257279001171c9.2c36671da7f1b6c9482575de002e1f14 $ Body.0.3D8。” filename= "blob" filename = “blob”

Content-Type: image/png 内容类型:image / png

------WebKitFormBoundaryW0NQVOkdrfkYGWV3-- ------ WebKitFormBoundaryW0NQVOkdrfkYGWV3--

根据FormData ,您应该能够为data.append()调用添加一个filename参数,如下所示:

data.append("ImageFileField", blob, "imageFilename.png");

if you want to modify the filename in the blob itself, just add a key called "name" 如果你想修改blob本身的文件名,只需添加一个名为“name”的键

blob.name = "imageFilename.png"

After that your JS functions should be able to pick it up. 之后你的JS函数应该能够获取它。 I'm using jQuery File Upload and this works with it. 我正在使用jQuery文件上传,这适用于它。

i faced same problem that during upload, file name not a assign to multipart with blob object but after a lots of google and RND . 我面临同样的问题,在上传过程中,文件名不是分配给具有blob对象的多部分,而是在大量的google和RND之后。 i find simple and best approach for this problem. 我找到了解决这个问题的简单方法。

 let file = event.target.files[0];
 this.fileName = file.name;   // Like : abc.jpeg

 this.croppedImage = file  //blob object after cropping
 const formData = new FormData();
 formData.append('file',this.croppedImageSend,this.fileName);
 this.http.post(url, formData, headersOptions) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM