angularformsgoogle-cloud-platformfile-upload

Angular file upload on GCP causes strange characters to be shown in text-editor or encoding


I used following code to upload a image to Google cloud platform(GCP). The upload is successful but it's not opening after download. When inspected through Chrome browser "response" terminal. I see "--WebkitFormBoundar" at the end of the uploaded file which causes it corruped. Any ideas how to fix it?

<form method ="post" enctype="multipart/form-data" accept-charset="UTF-8">
    <input title="upload" #fileInput type="file" class="display-none" (change)="onFileChange($event, item)" />
    <button title="Manage Files" (click)="manageDialog($event, item)"></button>
    <button icon="pi-upload" title="Upload File" (click)="fileInput.click()" ></button>
</form>

enter image description here

enter image description here

Original image size: 44.1 kb

Corrupted image size: 44.3 kb

It looks like dumb question or scenario but this 0.2 kb size diff causes corruption in Multipart/form-data file upload. Thanks for your help.

I was part of original dev team at amazing web time tracker.


Solution

  • It is weird but here is the solution:

    Remove the enctype="multipart/form-data" from HTML form section.

    In Javascript POST call, update the code as below:

    fetch("http://example.com/path/upload.php", {
                    method: 'PUT',
                    body: event.target.files[0],
                    headers: {
                    'Content-Type': (event.target.files[0]).type
                    }
                })
    

    If you have formdata, remove it (these lines were responsible for corruption and unintended file size increases):

    // const formData = new FormData();
    // formData.append('file', file);
    

    Summary:

    1. We remove unwanted enctype
    2. We remove formData which might add "webkit-boundary" garbage text to uploaded file.
    3. We pass the file data event.target.files[0] directly in Fetch/HTTP API's body param and set file-type/content-type properly from (event.target.files[0]).type
    4. Some other posts suggest setting 'Content-Type': undefined which may be incorrect and it didn't work out for us.
    5. Now the uploaded file is corruption-free; mainly .xlsx or .ppt or other complex file formats are uploaded successfully.

    Notes: I'm co-dev at TimeOnSite for web.