【问题标题】:Can not upload image file无法上传图片文件
【发布时间】:2019-06-22 23:56:29
【问题描述】:

我想使用 Angular、Node.js 和 Mongoose (GridFS) 上传和保存单个或多个图像。 保存图像的另一种方法是 Base64,但我想使用 GridFs。

使用 Angular 7。

在后端,我只看到 req.file 未定义,req.body {} 为空。 我将我的文件数据附加到 formData 并通过 Angular 将其传递给 HTTP 请求。在console.log(this.files) 上,我可以在浏览器控制台中看到数据。我也用 Postman 测试过。

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>

角度

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 {}    
        });
    }
}

结果应该使用 Gridfs 将图像上传到 MongoDB,我需要再次检索或删除。

我可以在浏览器中将 formData 视为 file: binary。

Request Header

【问题讨论】:

    标签: node.js angular mongoose


    【解决方案1】:

    替换这个

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

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

    【讨论】:

    • 同样的问题。我也尝试过使用 JSON.stringyfy。奇怪
    • 我只是注意到你正在尝试追加文件,替换 onFileChange(event) { if (event.target.files && event.target.files.length) { this.files = event.target .文件; } } to onFileChange(event) { if (event.target.files && event.target.files.length) { // this.file 的类型是 File this.file = event.target.files[0]; } } ```
    • 获取未定义的 req.file 和 req.body.file
    • 阅读此article 我认为您缺少与您的multer 配置相关的内容
    猜你喜欢
    • 2021-07-01
    • 2015-01-08
    • 2015-06-17
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 2019-05-31
    相关资源
    最近更新 更多