如何正确使用angular和multer上传文件?

时间:2020-05-27 02:55:36

标签: javascript node.js angular multer

问题:

我已经使用express js使用angular和multer开发了文件上传。但是当我尝试上传文件时,它会不断显示此错误。

enter image description here

onSelectImage(event) {
    const file: File = event.target.files[0];
    if (file) {
      if (file.size / 1048576 < 2) {
        if (file.type === "image/jpeg" || file.type === "image/png") {
          this.fileUploadService.onLoad(file).subscribe(data=>{
            console.log("upload +++++", data);
          })
          this.previewSelectedImage(file);
        } else {
          this.openSnackBar("Image type must be jpeg or png", "Error");
        }
      } else {
        this.openSnackBar(
          "Image size not match. Image size must be smaller than 2MB",
          "Error"
        );
      }
    }
  }

这是我的服务文件代码。

import { Injectable } from "@angular/core";
import {
  HttpClient,
  HttpHeaders,
  HttpEvent,
  HttpErrorResponse,
  HttpEventType,
} from "@angular/common/http";
import { map } from "rxjs/operators";
import {
  BASE_URL_ADMIN,
  BASE_URL_PATIENT,
} from "../../../app-main/config/enum.config";

@Injectable({
  providedIn: "root",
})
export class FileUploadServiceService {
  ref: any;

  constructor(private httpClient: HttpClient) {}

  onLoad(fileToUpload: File) {
    const path = BASE_URL_PATIENT + "user/patPic";
    let headers = new HttpHeaders();
    const formData = new FormData();
    formData.append("patPic", fileToUpload, fileToUpload.name);
    console.log(formData);
    console.log(fileToUpload.name);
    return this.httpClient.post(path, formData, {
      headers,
      reportProgress: true,
      observe: "events",
    });
  }
}

这就是我在express.js控制器中编写代码的方式。

const multer = require("multer");
const storage = multer.diskStorage({
  destination: function(req, file, cb) {
    cb(null,  "./uploads/");
  },
  filename: function(req, file, cb) {
    cb(null, new Date().toISOString().replace(/:/g,'-') + file.originalname);
  }
});

const fileFilter = (req, file, cb) => {
  //reject file
  if (file.mimetype === "image/jpeg" || file.mimetype === "image/png" || file.mimetype === "application/pdf") {
    cb(null, true);
  } else {
    cb(null, false);
  }
};
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 //1Mb
  },
  fileFilter: fileFilter
});


router.post("/patPic", upload.single("patPic"), (req, res, next) => {
  console.log(req.file);
  res.status(200).json({ fileSrc: req.file.path });
});

在index.js文件中,我配置了跨域策略。

app.use(function(req, res, next) {
    var allowedOrigins = [
      "http://localhost:4200"
    ];
    var origin = req.headers.origin;
    console.log(origin)
    console.log(allowedOrigins.indexOf(origin) > -1)
    // Website you wish to allow to
    if (allowedOrigins.indexOf(origin) > -1) {
      res.setHeader("Access-Control-Allow-Origin", origin);
    }

    // res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");

    // Request methods you wish to allow
    res.setHeader(
      "Access-Control-Allow-Methods",
      "GET, POST, OPTIONS, PUT, PATCH, DELETE"
    );

    // Request headers you wish to allow
    res.setHeader(
      "Access-Control-Allow-Headers",
      "X-Requested-With,content-type,Authorization"
    );

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader("Access-Control-Allow-Credentials", true);

    // Pass to next layer of middleware
    next();
  });

上传文件时,它会在服务器日志中显示在服务器中。

SyntaxError:意外令牌-JSON中的位置0 在JSON.parse() 在createStrictSyntaxError(/home/hrm/Generalpublicapp/node_modules/body-parser/lib/types/json.js:158:10) 在解析时(/home/hrm/Generalpublicapp/node_modules/body-parser/lib/types/json.js:83:15) 在/home/hrm/Generalpublicapp/node_modules/body-parser/lib/read.js:121:18 在invokeCallback(/home/hrm/Generalpublicapp/node_modules/raw-body/index.js:224:16) 完成时(/home/hrm/Generalpublicapp/node_modules/raw-body/index.js:213:7) 在IncomingMessage.onEnd(/home/hrm/Generalpublicapp/node_modules/raw-body/index.js:273:7) 在IncomingMessage.emit(events.js:322:22) 在endReadableNT(_stream_visible.js:1187:12) 在processTicksAndRejections(internal / process / task_queues.js:84:21)

有人可以帮助我解决此问题吗?我尝试了很多,以找到解决该问题的方法。但是我做不到。非常感谢。

0 个答案:

没有答案