0

Here is my problem:

I'm writing an angular app, I use App Engine and Google Cloud Storage as the backend (JAVA 8). Now I have text, and I want to save it to my database. Using cloud storage I need this text to be saved as a file. One manner to do that would be to convert my string into a file Object and send it to server via a multipart request.

How can I do that?

Here is my code so far (the aim of that code is to send a photo plus a text description):

  uploadAlbum(index:number){
    const formData = new FormData();
    //`myPhoto` is a file created with the <input type="file"> tag
    formData.append('file', myPhoto, '/gcs/my-bucket/' + index +'/cover/cover.jpg');
    //here is my problem here `description` is not a file
    formData.append('description', description, '/gcs/my-bucket/' + index +'/cover/cover.txt');
    this.http.post('/api/photos',formData).subscribe(
      (data: any) => {
        response = data;
      },
       err => {
         console.log(err)
        }
      );
  }

As description variable is a string, I get the following error on my console:

ERROR TypeError: "Argument 2 of FormData.append is not an object."

NOTE: Even if that can seem out of subject I added tags for the backend server on my post as I'm open to solve this issue creating a file on the backend also.

alextru
  • 441
  • 2
  • 12
JSmith
  • 4,519
  • 4
  • 29
  • 45
  • Possible duplicate of [Saving a text file on server using JavaScript](https://stackoverflow.com/questions/15722765/saving-a-text-file-on-server-using-javascript) – saitama May 07 '19 at 19:42
  • In [this question](https://stackoverflow.com/questions/23024460/javascript-i-created-a-blob-from-a-string-how-do-i-get-the-string-back-out) they created a blob (what formData needs, according to [JS docs](https://www.javascripture.com/FormData)) from a string. Can you try this with `description`? – alextru May 08 '19 at 15:03

1 Answers1

0

description is not a file because probably it's not present on the client side.

formData.append() is used to append the files with formData to upload them with form data.

Well you can not save a file to server using javascript.

see it has already been answerd here (Saving a text file on server using JavaScript)

saitama
  • 699
  • 1
  • 9
  • 21
  • `description` is a string like `"hello world!"` I know I can pass it as a second argument to `append(attributeName, content)` but I would like to pass in the path like `append(attributeName, file, filename)` for this I need description to be converted as a file object. Btw thanks for your answer but do you know how I can do that? – JSmith May 07 '19 at 20:38
  • well if you are using nodeJs you can use [File System](https://nodejs.org/api/fs.html) this module provides an API for interacting with the file system. – saitama May 07 '19 at 20:46
  • I'm not using nodejs :( – JSmith May 07 '19 at 20:48