简体   繁体   中英

Can not upload image file

I want to upload and save single or multiple images with Angular, Node.js and Mongoose (GridFS). The other way to save the image is Base64 but I want to work with GridFs.

Using Angular 7.

In the backend, I just see req.file is undefined and req.body is {} empty. I append my file data into formData and pass it into HTTP request over Angular. On console.log(this.files) I can see the data in the Browser console. I've tested with Postman as well.

Postman request result

HTML

<mat-step [stepControl]="photoForm">
  <form [formGroup]="photoForm">
    <ng-template matStepLabel>Photos</ng-template>
    <div class="container">
      <div class="imagePreview" *ngFor="let x of imageSrc" (click)="deleteImage($event)">
        <img class="img" [src]="x" />
      </div>
    </div>
    <input type="file" multiple (change)="onFileChange($event)" #fileInput style="display: none" />
    <button (click)="fileInput.click()">Select File</button>
  </form>
</mat-step>

Angular

onFileChange(event) {
  if (event.target.files && event.target.files.length) {
    this.files = event.target.files;
  }

  onSubmit() {
    const uploadData = new FormData();
    uploadData.append('myFile', this.files, this.files.name);

    this.http.post(url + '/api/upload', uploadData).subscribe((item) => {
      console.log(item);
    });
  }
}

Node.js

import * as compression from "compression";
import * as express from "express";
import * as bodyParser from "body-parser";
import * as mongoose from "mongoose";
import { Routes } from "./routes/routes";
import * as cors from 'cors';
import { urlencoded } from "body-parser";
import { Contact } from "./routes/contact";
import { AddTour } from "./routes/addTour";
const path = require('path');
const mongoURI = 'mongodb://127.0.0.1/testDB';
let gfs;

//GridFS
const crypto = require('crypto');
const mongoose = require('mongoose');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override');

class App {
  public app: express.Application;
  public addTourObj: AddImages = new AddImages();

  constructor() {
    this.app = express();
    this.config();
    this.addTourObj.addImage(this.app);
    this.connectMongoDB();

    /** Setting up storage using multer-gridfs-storage */
    // Create storage engine
    const storage = new GridFsStorage({
      url: mongoURI,
      file: (req, file) => {
        return new Promise((resolve, reject) => {
          crypto.randomBytes(16, (err, buf) => {
            if (err) {
              return reject(err);
            }
            const filename = buf.toString('hex') + path.extname(file.originalname);
            const fileInfo = {
              filename: filename,
              bucketName: 'uploads'
            };
            resolve(fileInfo);
          });
        });
      }
    });

    var upload = multer({ //multer settings for single upload
      storage: storage
    }).single('file');        
  }

  private config() {
    this.app.use(cors());
    this.app.options('*', cors());
    this.app.use(bodyParser.json());
    this.app.use(urlencoded({ extended: true }));
    this.app.use(compression());
  }

  private connectMongoDB() {
    const conn = mongoose.createConnection(mongoURI);
    conn.once('open', () => {
      // Init stream
      gfs = Grid(conn.db, mongoose.mongo);
      gfs.collection('uploads');
    });    
  }
}

export default new App().app;

Node.js AddImage.ts

import { Request, Response } from "express";
import { request } from "http";

export class AddImage {

    public addImage(app): void {
        app.route('/api/upload').post((req, res) => {
            console.log(req.file) // is undefined
            console.log(req.body) // is empty {}    
        });
    }
}

The result should be uploaded the image into MongoDB with Gridfs which I need to retrieve or delete again.

I can see the formData as file: binary in the browser.

Request Header

replace this

uploadData.append('myFile', this.files, this.files.name);

with

uploadData.append('file', this.files, this.files.name);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM