Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript/jQuery Append to FormData() returns 'undefined'

I'm trying to do a simple file upload using jQuery. I have a file input in my HTML like so:

<form id="PhotoUploadForm" action="/some/correct/url" method="post" enctype="multipart/form-data">
            <input type="file" id="uploadPhoto" accept="image">
</form>

I also have some JavaScript / jQuery bound to the change event of the input, like so:

   $('#uploadPhoto').on("change", function (event) {

        var fileData = this.files[0];
        var data = new FormData();
        data.append('image',fileData);
        data.append('content','What could go wrong');
        console.log(data.image, data.content); // this outputs 'undefined undefined' in the console

        $.ajax ({
            url: "/some/correct/url",
            type: 'POST',
            data: data,
            processData: false,
            beforeSend: function() {
               console.log('about to send');
            },
            success: function ( response ) {                   
                console.log( 'now do something!' )
            },
            error: function ( response ) {
                console.log("response failed");
            }
        });
    });

I noticed I was getting a 500 error! Most likely the data is incorrect, I know the URL is good. So I tried to output the data to the console and I noticed that my data appends return 'undefined'

console.log(data.image, data.content); // this outputs 'undefined undefined' in the console

when I console.log(data) I get the following:

FormData {append: function}__proto__: FormData

Am I doing something wrong here? Why are data.image & data.content undefined? When I output the this.files[0] I get the following:

File {webkitRelativePath: "", lastModified: 1412680079000, lastModifiedDate: Tue Oct 07 2014 13:07:59 GMT+0200 (CEST), name: "2575-Web.jpg", type: "image/jpeg"…}lastModified: 1412680079000lastModifiedDate: Tue Oct 07 2014 13:07:59 GMT+0200 (CEST)name: "2575-Web.jpg"size: 138178type: "image/jpeg"webkitRelativePath: ""__proto__: File

So the issue isn't with the image. Am I correct?

like image 451
Mark Sandman Avatar asked Oct 13 '14 13:10

Mark Sandman


People also ask

Why FormData is undefined?

The "FormData is not defined Error" error occurs when we try to use the FormData() constructor on the server side, most commonly in a Node. js application. To solve the error, install and import the form-data npm package.

How do I append in FormData?

FormData Methodsappend(name, value) – add a form field with the given name and value , formData. append(name, blob, fileName) – add a field as if it were <input type="file"> , the third argument fileName sets file name (not form field name), as it were a name of the file in user's filesystem, formData.

What is new FormData ()?

The FormData interface provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using the fetch() or XMLHttpRequest.send() method. It uses the same format a form would use if the encoding type were set to "multipart/form-data" .

Can we send object in FormData?

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest . It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data.


1 Answers

Issue

You are misunderstanding the FormData object. A FormData object has only an .append() method, which doesn't append properties to it, but only stores the data provided. Hence, obviously, the .image and .content properties will be undefined.

If you want to create a object with the .image and .content properties you should instead create a regular object and then send it.

Workaround

To achieve what you want you have some options:

  1. Using FormData:
    • Call its constructor passing the <form> element as an argument, and it will do all the work for you.
    • OR: create the object and then use the .append() method.
  2. Use a regular object and send it.
  3. Use a regular object, convert it to JSON and send it using contentType: 'application/json'.

What option would you choose? It only depends on the back-end. If you are developing the back-end make sure you are retrieving the data from the POST request in the correct way, otherwise check the site and see what kind of data you'll need to send.

Option 1

Create the FormData object:

  • Method 1, let the constructor work for you:

    var form = document.getElementById("PhotoUploadForm"),
        myData = new FormData(form);
    
  • Method 2, do it by yourself:

    var fileData = this.files[0],
        myData = new FormData();
    
    myData.append('image', fileData);
    

Then, later in your code, you can send it:

$.ajax({
    url: "/some/correct/url",
    type: 'POST',
    data: myData, // here it is
    ...
});

Option 2

Create a regular object and send it:

var myData = {
        image: this.files[0]
    };

$.ajax({
    url: "/some/correct/url",
    type: 'POST',
    data: myData, // here it is
    ...
});

Option 3

var myData = {
        image: this.files[0]
    };

myData = JSON.stringify(myData); // convert to JSON

$.ajax({
    url: "/some/correct/url",
    type: 'POST',
    contentType: 'application/json',
    data: myData, // here it is
    ...
});
like image 148
Marco Bonelli Avatar answered Sep 30 '22 17:09

Marco Bonelli