(angular 8) Error occurred when converting a file or image to FormData due to an invalid value (Note: FormData object printed as Object Form{})

I encountered an issue where I am getting an invalid value from form data. The value appears correct in `this.fileData` with a size of 5701, but becomes empty when converted to form data - `{}` is logged when I console.log the form data. Additionally, accessing `formdata[0]` returns an undefined value.

The problem arises when I expect the backend to receive a valid file when the form data is posted, but instead it receives a picture with a size of 0. My suspicion is that the issue lies within the form data since it seems to be empty.

HTML snippet:

<div class="container">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <h3>Choose File</h3>            
            <div class="form-group">
                <input type="file" name="image" (change)="fileProgress($event)" />
            </div>
            <div *ngIf="fileUploadProgress">
                Upload progress: {{ fileUploadProgress }}
            </div>
            <div class="image-preview mb-3" *ngIf="previewUrl">
                <img [src]="previewUrl" height="300" />                 
            </div>

            <div class="mb-3" *ngIf="uploadedFilePath">
                {{uploadedFilePath}}
            </div>

            <div class="form-group">
                <button class="btn btn-primary"  (click)="onSubmit()">Submit</button>
            </div>
        </div>
    </div>
</div>

Typescript snippet:

import { Component, OnInit, Input } from '@angular/core';
import { HttpClient, HttpEventType } from '@angular/common/http';
import { UploadService } from '../../../model/shared/api/upload.service';
import { HttpHeaders } from '@angular/common/http';
import { LoginComponent } from '../../account/auth/login/login.component';
import { HttpClientModule } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
    //'Authorization': 'my-auth-token'
  })
};

@Component({
  selector: 'cd-upload',
  templateUrl: './upload.component.html',
  styleUrls: ['./upload.component.scss']
})

export class UploadComponent implements OnInit{
fileData: File = null;
previewUrl:any = null;
fileUploadProgress: string = null;
uploadedFilePath: string = null;

constructor(private uploadService: UploadService,private httpClient: HttpClient,private http: HttpClient) {}

fileProgress(fileInput: any) {
    this.fileData = <File>fileInput.target.files[0];
    this.preview();
}

preview() {
    var mimeType = this.fileData.type;
    if (mimeType.match(/image\/*/) == null) {
      return;
    }

    var reader = new FileReader();      
    reader.readAsDataURL(this.fileData); 
    reader.onload = (_event) => { 
        this.previewUrl = reader.result; 
    }
}

onSubmit() {
    const formData = new FormData(); 
    formData.append('files', this.fileData);
    console.log(this.fileData);
    console.log(formData[0]);
    console.log(formData);
    this.http.post('http://api', formData, {
        reportProgress: true,responseType: 'blob' as 'json',
        observe: 'events'   
    }) 
}

ngOnInit(){}


}

Backend Python Flask code:

@app.route('/bupload', methods=['GET', 'POST'])
def bupload():   
    result="Upload done";result1="Upload fail";result2="File not allowed";result3="No selected file";result4="No file part";form="123";
    print(request.files); print(request.files['files']);
    if 'files' not in request.files:
        flash('No file part');print(file);
        return result4
    file = request.files['files'];print(file);print("@0");
    if file.filename == '':
        flash('No selected file')
        return result3
    if file and allowed_file(file.filename):
        if(upload_First(form, file)):
            flash('Upload done');
            print("@");
            return result
        else:
            flash('Upload fail')
            return result1
    else:
        flash('File not allowed')
        return result2

Additional notes:

  • Backend can receive the value ImmutableMultiDict([('files', )]), but the IDF.jpg file has a size of 0.
  • Console.log(formData.get('files')) displays detailed information about the uploaded file.
  • Console.log(formData) shows an empty FormData object.

Answer №1

_event.target.result contains the file content

Send fileContent to the server


  handleFileInput(fileInput){
    var file = <File>fileInput.target.files[0];
    const formData = new FormData();
    var reader = new FileReader();      
    reader.readAsDataURL(file); 
    reader.onload = (_event) => { 
      formData.append('photo', _event.target.result);
      console.log(formData.get('photo'));
    }
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After transitioning to TypeScript, the CRA app is encountering issues loading CSS files compiled by SASS

My React application was originally created using create-react-app and I had been successfully loading scss files with the node-sass package. However, after deciding to switch to TypeScript following the steps outlined in , my css files are no longer being ...

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

An error is thrown when trying to retrieve Objects: Uncaught TypeError - Object function ParsePromise()

By obtaining a Document object with its id, the following code proceeds to locate corresponding sections based on the object. The document identifies a Parse object and document.toJSON converts this into a Javascript object. Furthermore, sections represent ...

Use a conditional statement for each element within the array

Below is the code I am currently using: if (res[0].toString() == "hello") { res[0] = "string"; }; While it works, I would like this logic to apply to all elements rather than just the first one. Is there a way to achieve this for every element in the ar ...

Angular - Dividing Functionality into Multiple Modules

I am currently working with two separate modules that have completely different designs. To integrate these modules, I decided to create a new module called "accounts". However, when I include the line import { AppComponent as Account_AppComponent} from &a ...

The download of package-lock.json is not initiated for a linked GitHub URL

I currently have two projects on GitHub. One is named "mylibrary" and the other is "test-project." In my "test-project," I have linked "mylibrary" using its GitHub URL in the package.json file as shown below. dependencies: { "mylibrary": "git+ssh://& ...

Ways to activate an event based on the dimensions (width/height) of

Exploring ways to implement an if statement based on specific width/height values using this code example. Check out the code snippet here My approach: <p id="confirmation">Try again!</p> <script> if (new dynamicSize.width() < ...

Display the item request form whenever a selection of an unidentified item is made using select2

I want to implement select2 for a company search feature. In case the desired company is not available in the existing dataset, I need to provide an option for users to request adding the company data. This is the HTML code: <head> <link href=& ...

Automatic placement of the cursor at the left end of the username field in the registration form is required

Hey there! I'm looking to customize the registration form on my WordPress website so that when a user clicks on any field, such as the username field, the cursor automatically moves to the left end of that field and the keyboard switches to ENG-US. ...

In JSF, the loading bar is hidden before the page is completely loaded

Currently, I am facing an issue with the loading bar. It seems to disappear before the page content is fully loaded. Ideally, I would like the loading bar to remain visible until the entire page has been loaded correctly. In the layout.xhtml file, I have ...

JS: Modifying this function to manage a click on a hyperlink

After following the guide provided here I have successfully implemented a drop down list that sends the value to an external PHP script, retrieves HTML output, and displays it in a "div" on the same page. It works flawlessly. My next objective is to send ...

When I close all of my tabs or the browser, I aim to clear the local storage

Could you recommend any strategies for clearing local storage upon closing the last tab or browser? I have attempted to use local storage and session storage to keep track of open and closed sessions in an array stored in local storage. However, this meth ...

Tips for automatically filling in fields when a button is clicked in a React application

I'm attempting to pre-fill the form fields that are duplicated with data from already filled fields. When I click the "Add Fields" button, new fields are replicated, but I want them to be pre-populated with data from existing fields. How can I access ...

ways to dynamically retrieve input values in PHP

Is there a way to dynamically add and remove data fields, as well as increase and decrease fields dynamically in PHP? I am looking to retrieve the subject value in an array or JSON format using PHP only. https://i.stack.imgur.com/HqDCz.png <div data-ro ...

npm not only loads the packages specified in my package.json file

Currently, I am working on a small project utilizing npm, bower, and grunt. Upon executing "npm install" on my personal computer, it seems to be loading an excessive amount of peculiar items (refer to attached screenshot). However, when performing the same ...

The React snackbar is mysteriously peeking out from behind the popup

While using the react-notifications-component snack bar, I encountered an issue where my snack bar was appearing behind the pop-up. Is there a way to fix this with z-index? I tried using <ReactNotification style={{ zIndex: 10000 }}/>, but it didn&ap ...

In order to ensure a valid JSON for parsing in JavaScript, one must reverse the usage of single quotes and double quotes. This adjustment

Received an API response structured like this: [{'name': 'men', 'slug': 'men'}, {'name': 'women', 'slug': 'women'}] After stringifying: const data = JSON.stringify(resp) " ...

Is there a way to eliminate a wrapper object from each element in a JSON array using JavaScript?

My knowledge of JavaScript is limited and I am facing a particular issue. The JSON document at hand looks like this: { "forecast": [ { "day-1": { "forecast_date": "2017-11-23", "morning": { "weather": { " ...

Ways to get a Discord bot to echo a message?

As a novice in the world of discord.js and bot creation, I am eager to implement a simple magic 8-ball inspired command. This command will allow users to ask the bot a question and receive a random answer in response. const commands = [ new SlashCommandBui ...

Loop through a list of form names using ng-repeat and send each form name to a JavaScript function when clicked

I have multiple forms within an ng-repeat loop, each with a different name. I need to pass the form data when a button inside the form is clicked. However, when I try to call it like this: checkSaveDisable(updateProductSale_{{productIndex}}) it thro ...