30
votes

I use event.clipboardData to get image from clipboard, and then upload it server, code:

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.

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?

This is the upload data detail:

Request Payload

------WebKitFormBoundaryW0NQVOkdrfkYGWV3
Content-Disposition: form-data; name="%%File.48257279001171c9.2c36671da7f1b6c9482575de002e1f14.$Body.0.3D8"; filename="blob"

Content-Type: image/png

------WebKitFormBoundaryW0NQVOkdrfkYGWV3--

3

3 Answers

60
votes

According to FormData, you should be able to add a filename parameter to your data.append() call as follows:

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

if you want to modify the filename in the blob itself, just add a key called "name"

blob.name = "imageFilename.png"

After that your JS functions should be able to pick it up. I'm using jQuery File Upload and this works with it.

7
votes

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 . 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)