Image manipulation with nodejs and Ionic

Asked

Viewed 138 times

0

I have an Ionic application, in it I have to send an image converted to Base64 for an api, and the api for the database. I was getting error by the size of the payload, I found on the internet about using JSON.stringfy, apparently worked, however, I can not receive in the API and store in the database. Follows the codes used:

To perform the conversion :

getPhoto() {
    let options = {
      maximumImagesCount: 1
    };
    this.imagePicker.getPictures(options).then((results) => {
      for (var i = 0; i < results.length; i++) {
          this.imgPreview = results[i];
          this.base64.encodeFile(results[i]).then((base64File: string) => {
            this.regData.avatar = base64File;
            this.novoCredenciadoModel.caminho = this.regData.avatar;
          }, (err) => {
            console.log(err);
          });
      }
    }, (err) => { });
  }

To send to the past:

register() {
    this.novoCredenciadoService.enviar(this.novoCredenciadoModel).subscribe((result) => {
      // this.loading.dismiss();
      let alert = this.alertCtrl.create({
        title: 'Registration Successful',
        subTitle: 'Great! Your registration is success',
        buttons: ['OK']
      });
      alert.present();
    }, (err) => {
      console.log(err);
      // this.loading.dismiss();
      let alert = this.alertCtrl.create({
        title: 'Registration Failed',
        subTitle: 'Oh no! Your registration is failed',
        buttons: ['OK']
      });
      alert.present();
    });
  }

And in the past:

return this.http.post(Constants.CAMINHO_TESTE+api,JSON.stringify(corpoRequisicao))
    .pipe(map((resp: Response) =>{
      console.log(JSON.stringify(corpoRequisicao));
      console.log("post/response");
      console.log (resp);
      }));

In the API, the following, to receive the data:

var received = JSON.stringify(req);

var nome = received.nome;
var email = received.email;
var telefone = received.telefone;
var endereco = received.endereco;
var cnpj = received.cnpj;
var categoria = received.categoria;
var caminho = received.caminho; //caminho seria a img em base64

But I get the following error:

Syntaxerror: Unexpected token P in JSON at position 0

Some way to perform such a function?

Edit:

 handler: () => {
            this.http.post("minharota/api/novo", JSON.stringify(postData), requestOptions)
              .subscribe(data => {

Postdata is the data that comes from the form, which I think are correct because when loguei was normal.

1 answer

1


  1. You need to move the image to an independent upload endpoint via your api. Ex.: POST /api/uploadimage .
  2. The necessary key in your header for the request:

    • Content-Type: application/x-www-form-urlencoded
    • Body: a parameter with some name (example: image) and its value would be the image in Base64
  3. On your route in the Node API: (there are other ways to do this, many even more elegant)

    var imageEncoding = req.body.image.replace(/ /g, "+");
    

    Variable imageEncoding can be saved in a varchar field, string, etc.

  4. Don’t forget to set up your api to receive content via larger request, if that’s your case.

    Example with Node and Express:

    app.use(bodyParser.urlencoded({extended: true, limit: '50mb'}));
    app.use(bodyParser.json({limit: '50mb'}));
    
  5. If you don’t use any tools for communication tests with Rest Apis, I suggest you use some (the community uses Postman a lot), because they are more minimalist and make you gain time with these tests.

I hope I’ve helped.

  • Performing this imageEncoding, I will then be able to show the image in the app normally or I would have to perform some specific coding ?

  • You could, and you don’t need a code name. This "req.body.image.replace(/g, "+");" is required to handle the content that was transformed by "application/x-www-form-urlencoded" during the request.

  • I was testing here, and I came across the following scenario: If I don’t use the bodyparser there to increase the limit, it gives payload to large, OK. But if I use it, it says that the image comes Undefined, and the error in parse. I did exactly as you recommended, is that something left behind ?

  • Please send the Request code that is being fired to your api?

  • edited the question, put at the end

    1. the image should not be passed as json. It should be passed like this, assuming the parameter name is image: image=imagemEmBase64
    1. The only parameter that should be sent is the one in the image 3. You can’t forget to pass Header: Content-Type: application/x-www-form-urlencoded
  • example of an HTTP message for this purpose: PUT /api/users/alterarImagem HTTP/1.1 Host: localhost:3000 Authorization: Bearer eyJ0eXAiOJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIOiIwNjYuMjcwLI5Ni00MiJ9.9lX3rMFi42EI1zmRcLzalw_S874N7dAK8_MS66BOMQ Content-Type: application/x-www-form-urlencoded Cache-Control: no-cache Postman-Token: afe76ca1-d3c1-6eb6-bd1c-4c20d1e47da9 image=/9j/4AQSkZJRgABAQEBLAE ...

  • First use Postman, make sure the HTTP message exchange works and then you implement it in the technology you want

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.