Multer to Store Image File DiskStorage Error Server Error












0















I have a blogging app built with MEAN stack, the app has been working fine for all time.
It broke after I added upload image feature using Multer node.js package.



This is my folder structure:



enter image description here



The directory where I want to store my image:
serverimgStore



My multer configuration is:



  const express = require("express");
const multer = require("multer");
const Post = require("../models/post");

const router = express.Router();

const MIME_TYPE_MAP = {
'imgStore/png': 'png',
'imgStore/jpeg': 'jpg',
'imgStore/jpg': 'jpg'
}

const storage = multer.diskStorage({
destination: (req, file, cb) => {
// called when multer tries to save file
// request, file, callback
const isValid = MIME_TYPE_MAP[file.mimetype];
let error = new Error("Invalid mime type");
if (isValid) { // if its known extention set error to null
error = null;
}

console.log('before cb error line.');
cb(error, "server/imgStore"); // this path is relative to server.js not route.js
},
filename: (req,file,cb) => {
const name = file.originalname.toLowerCase().split(' ').join('-');//replace whitespace with dash
const ext = MIME_TYPE_MAP[file.mimetype];
cb(null, name + '-' + Date.now()+ '.' + ext)
}
});


My Form in the html:



<form [formGroup]="form" (submit)="onSavePost(postForm)" #postForm="ngForm" *ngIf="!isLoading">
<!--create directive formGroup with the name of instance we created in ts file
in the input tag below, we removed name, instead we use formControlName
-->
<mat-card-title>{{mode}} your post here:</mat-card-title>
<mat-form-field floatLabel="never"> <!-- remove the float label-->
<input
matInput
type="text"
formControlName="title"
placeholder="Title"
>
<mat-error *ngIf="form.get('title').invalid">
<mat-error *ngIf="form.get('title').errors.required">
Title is required!
</mat-error>
<mat-error *ngIf="form.get('title').errors.minlength">
Title needs at least 4 characters !
</mat-error>
</mat-error>
</mat-form-field>
<mat-form-field floatLabel="never">
<textarea
matInput
rows="6"
formControlName="content"
placeholder="Content"
>
</textarea>
<mat-error *ngIf="form.get('content').invalid">
<div *ngIf="form.get('content').errors.required">
Cannot be empty!
</div>
</mat-error>
</mat-form-field>
<div class="img-loader">
<button (click)="filePicker.click()" mat-stroked-button type="button" color="primary">Upload Image</button>
<input type="file" #filePicker (change)="onImagePicked($event)"> <!--localRef is filePicker-->
</div>
<div class="image-preview" *ngIf="imagePreview!=='' && imagePreview && form.get('image').valid">
<img [src]="imagePreview" [alt]="form.value.title">
</div>

<div *ngIf="form.get('image').invalid" style="margin-bottom:20px;">
<mat-error *ngIf="imagePreview && form.get('image').errors.invalidMimeType">
Only files of [jpg, jpeg, png] are allowed to upload!
</mat-error>
</div>

<button
mat-raised-button
color="primary"
type="submit"
[disabled]="postForm.invalid">Save Post</button>
<!--I really prefer disable the submit button when its still invalid input!-->

</form>


Once I pick image by click upload image button and pick an image that is acceptable type: jpg, jpeg, png



Click 'Save Post' button will gets the error message in my node console:



enter image description here



I can stuck on getting it to work, will appreciate some help !










share|improve this question



























    0















    I have a blogging app built with MEAN stack, the app has been working fine for all time.
    It broke after I added upload image feature using Multer node.js package.



    This is my folder structure:



    enter image description here



    The directory where I want to store my image:
    serverimgStore



    My multer configuration is:



      const express = require("express");
    const multer = require("multer");
    const Post = require("../models/post");

    const router = express.Router();

    const MIME_TYPE_MAP = {
    'imgStore/png': 'png',
    'imgStore/jpeg': 'jpg',
    'imgStore/jpg': 'jpg'
    }

    const storage = multer.diskStorage({
    destination: (req, file, cb) => {
    // called when multer tries to save file
    // request, file, callback
    const isValid = MIME_TYPE_MAP[file.mimetype];
    let error = new Error("Invalid mime type");
    if (isValid) { // if its known extention set error to null
    error = null;
    }

    console.log('before cb error line.');
    cb(error, "server/imgStore"); // this path is relative to server.js not route.js
    },
    filename: (req,file,cb) => {
    const name = file.originalname.toLowerCase().split(' ').join('-');//replace whitespace with dash
    const ext = MIME_TYPE_MAP[file.mimetype];
    cb(null, name + '-' + Date.now()+ '.' + ext)
    }
    });


    My Form in the html:



    <form [formGroup]="form" (submit)="onSavePost(postForm)" #postForm="ngForm" *ngIf="!isLoading">
    <!--create directive formGroup with the name of instance we created in ts file
    in the input tag below, we removed name, instead we use formControlName
    -->
    <mat-card-title>{{mode}} your post here:</mat-card-title>
    <mat-form-field floatLabel="never"> <!-- remove the float label-->
    <input
    matInput
    type="text"
    formControlName="title"
    placeholder="Title"
    >
    <mat-error *ngIf="form.get('title').invalid">
    <mat-error *ngIf="form.get('title').errors.required">
    Title is required!
    </mat-error>
    <mat-error *ngIf="form.get('title').errors.minlength">
    Title needs at least 4 characters !
    </mat-error>
    </mat-error>
    </mat-form-field>
    <mat-form-field floatLabel="never">
    <textarea
    matInput
    rows="6"
    formControlName="content"
    placeholder="Content"
    >
    </textarea>
    <mat-error *ngIf="form.get('content').invalid">
    <div *ngIf="form.get('content').errors.required">
    Cannot be empty!
    </div>
    </mat-error>
    </mat-form-field>
    <div class="img-loader">
    <button (click)="filePicker.click()" mat-stroked-button type="button" color="primary">Upload Image</button>
    <input type="file" #filePicker (change)="onImagePicked($event)"> <!--localRef is filePicker-->
    </div>
    <div class="image-preview" *ngIf="imagePreview!=='' && imagePreview && form.get('image').valid">
    <img [src]="imagePreview" [alt]="form.value.title">
    </div>

    <div *ngIf="form.get('image').invalid" style="margin-bottom:20px;">
    <mat-error *ngIf="imagePreview && form.get('image').errors.invalidMimeType">
    Only files of [jpg, jpeg, png] are allowed to upload!
    </mat-error>
    </div>

    <button
    mat-raised-button
    color="primary"
    type="submit"
    [disabled]="postForm.invalid">Save Post</button>
    <!--I really prefer disable the submit button when its still invalid input!-->

    </form>


    Once I pick image by click upload image button and pick an image that is acceptable type: jpg, jpeg, png



    Click 'Save Post' button will gets the error message in my node console:



    enter image description here



    I can stuck on getting it to work, will appreciate some help !










    share|improve this question

























      0












      0








      0








      I have a blogging app built with MEAN stack, the app has been working fine for all time.
      It broke after I added upload image feature using Multer node.js package.



      This is my folder structure:



      enter image description here



      The directory where I want to store my image:
      serverimgStore



      My multer configuration is:



        const express = require("express");
      const multer = require("multer");
      const Post = require("../models/post");

      const router = express.Router();

      const MIME_TYPE_MAP = {
      'imgStore/png': 'png',
      'imgStore/jpeg': 'jpg',
      'imgStore/jpg': 'jpg'
      }

      const storage = multer.diskStorage({
      destination: (req, file, cb) => {
      // called when multer tries to save file
      // request, file, callback
      const isValid = MIME_TYPE_MAP[file.mimetype];
      let error = new Error("Invalid mime type");
      if (isValid) { // if its known extention set error to null
      error = null;
      }

      console.log('before cb error line.');
      cb(error, "server/imgStore"); // this path is relative to server.js not route.js
      },
      filename: (req,file,cb) => {
      const name = file.originalname.toLowerCase().split(' ').join('-');//replace whitespace with dash
      const ext = MIME_TYPE_MAP[file.mimetype];
      cb(null, name + '-' + Date.now()+ '.' + ext)
      }
      });


      My Form in the html:



      <form [formGroup]="form" (submit)="onSavePost(postForm)" #postForm="ngForm" *ngIf="!isLoading">
      <!--create directive formGroup with the name of instance we created in ts file
      in the input tag below, we removed name, instead we use formControlName
      -->
      <mat-card-title>{{mode}} your post here:</mat-card-title>
      <mat-form-field floatLabel="never"> <!-- remove the float label-->
      <input
      matInput
      type="text"
      formControlName="title"
      placeholder="Title"
      >
      <mat-error *ngIf="form.get('title').invalid">
      <mat-error *ngIf="form.get('title').errors.required">
      Title is required!
      </mat-error>
      <mat-error *ngIf="form.get('title').errors.minlength">
      Title needs at least 4 characters !
      </mat-error>
      </mat-error>
      </mat-form-field>
      <mat-form-field floatLabel="never">
      <textarea
      matInput
      rows="6"
      formControlName="content"
      placeholder="Content"
      >
      </textarea>
      <mat-error *ngIf="form.get('content').invalid">
      <div *ngIf="form.get('content').errors.required">
      Cannot be empty!
      </div>
      </mat-error>
      </mat-form-field>
      <div class="img-loader">
      <button (click)="filePicker.click()" mat-stroked-button type="button" color="primary">Upload Image</button>
      <input type="file" #filePicker (change)="onImagePicked($event)"> <!--localRef is filePicker-->
      </div>
      <div class="image-preview" *ngIf="imagePreview!=='' && imagePreview && form.get('image').valid">
      <img [src]="imagePreview" [alt]="form.value.title">
      </div>

      <div *ngIf="form.get('image').invalid" style="margin-bottom:20px;">
      <mat-error *ngIf="imagePreview && form.get('image').errors.invalidMimeType">
      Only files of [jpg, jpeg, png] are allowed to upload!
      </mat-error>
      </div>

      <button
      mat-raised-button
      color="primary"
      type="submit"
      [disabled]="postForm.invalid">Save Post</button>
      <!--I really prefer disable the submit button when its still invalid input!-->

      </form>


      Once I pick image by click upload image button and pick an image that is acceptable type: jpg, jpeg, png



      Click 'Save Post' button will gets the error message in my node console:



      enter image description here



      I can stuck on getting it to work, will appreciate some help !










      share|improve this question














      I have a blogging app built with MEAN stack, the app has been working fine for all time.
      It broke after I added upload image feature using Multer node.js package.



      This is my folder structure:



      enter image description here



      The directory where I want to store my image:
      serverimgStore



      My multer configuration is:



        const express = require("express");
      const multer = require("multer");
      const Post = require("../models/post");

      const router = express.Router();

      const MIME_TYPE_MAP = {
      'imgStore/png': 'png',
      'imgStore/jpeg': 'jpg',
      'imgStore/jpg': 'jpg'
      }

      const storage = multer.diskStorage({
      destination: (req, file, cb) => {
      // called when multer tries to save file
      // request, file, callback
      const isValid = MIME_TYPE_MAP[file.mimetype];
      let error = new Error("Invalid mime type");
      if (isValid) { // if its known extention set error to null
      error = null;
      }

      console.log('before cb error line.');
      cb(error, "server/imgStore"); // this path is relative to server.js not route.js
      },
      filename: (req,file,cb) => {
      const name = file.originalname.toLowerCase().split(' ').join('-');//replace whitespace with dash
      const ext = MIME_TYPE_MAP[file.mimetype];
      cb(null, name + '-' + Date.now()+ '.' + ext)
      }
      });


      My Form in the html:



      <form [formGroup]="form" (submit)="onSavePost(postForm)" #postForm="ngForm" *ngIf="!isLoading">
      <!--create directive formGroup with the name of instance we created in ts file
      in the input tag below, we removed name, instead we use formControlName
      -->
      <mat-card-title>{{mode}} your post here:</mat-card-title>
      <mat-form-field floatLabel="never"> <!-- remove the float label-->
      <input
      matInput
      type="text"
      formControlName="title"
      placeholder="Title"
      >
      <mat-error *ngIf="form.get('title').invalid">
      <mat-error *ngIf="form.get('title').errors.required">
      Title is required!
      </mat-error>
      <mat-error *ngIf="form.get('title').errors.minlength">
      Title needs at least 4 characters !
      </mat-error>
      </mat-error>
      </mat-form-field>
      <mat-form-field floatLabel="never">
      <textarea
      matInput
      rows="6"
      formControlName="content"
      placeholder="Content"
      >
      </textarea>
      <mat-error *ngIf="form.get('content').invalid">
      <div *ngIf="form.get('content').errors.required">
      Cannot be empty!
      </div>
      </mat-error>
      </mat-form-field>
      <div class="img-loader">
      <button (click)="filePicker.click()" mat-stroked-button type="button" color="primary">Upload Image</button>
      <input type="file" #filePicker (change)="onImagePicked($event)"> <!--localRef is filePicker-->
      </div>
      <div class="image-preview" *ngIf="imagePreview!=='' && imagePreview && form.get('image').valid">
      <img [src]="imagePreview" [alt]="form.value.title">
      </div>

      <div *ngIf="form.get('image').invalid" style="margin-bottom:20px;">
      <mat-error *ngIf="imagePreview && form.get('image').errors.invalidMimeType">
      Only files of [jpg, jpeg, png] are allowed to upload!
      </mat-error>
      </div>

      <button
      mat-raised-button
      color="primary"
      type="submit"
      [disabled]="postForm.invalid">Save Post</button>
      <!--I really prefer disable the submit button when its still invalid input!-->

      </form>


      Once I pick image by click upload image button and pick an image that is acceptable type: jpg, jpeg, png



      Click 'Save Post' button will gets the error message in my node console:



      enter image description here



      I can stuck on getting it to work, will appreciate some help !







      angularjs typescript mean-stack multer






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Dec 31 '18 at 9:31









      Edward SunEdward Sun

      325




      325
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53985812%2fmulter-to-store-image-file-diskstorage-error-server-error%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53985812%2fmulter-to-store-image-file-diskstorage-error-server-error%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Mossoró

          Error while reading .h5 file using the rhdf5 package in R

          Pushsharp Apns notification error: 'InvalidToken'