【问题标题】:How to save file locally and save path on database using multer on angular如何在本地保存文件并在数据库中使用 multer on angular 保存路径
【发布时间】:2019-08-30 09:09:25
【问题描述】:

我有一个表格,要求提供 Angular 中 pdf 文件的详细信息。我想将该文件上传到 PDFS 文件夹,而不是数据库。所以在这里我想做三件事:

  1. 如何使用带有 pdf 扩展名的用户标题重命名文件名
  2. 如何将该文件保存在 PDF 文件夹中
  3. 如何保存我们保存在数据库中的那个文件的路径。

技术:Angular、express、MongoDB、multer

如果在所有这些条件下已有任何示例可用,您可以提供给我一个链接。

【问题讨论】:

    标签: node.js angular angular6 mean-stack multer


    【解决方案1】:

    这是 express 节点和 mongo 端,用于将文件保存到 express 服务器本地的文件夹中。路径将

        const multer = require('multer');
        const path = require('path');
        const fs = require('fs');
        const DIR = path.join(__dirname, '../PDFS/');
        const storage = multer.diskStorage({
            destination: (req, file, cb) => {
                cb(null, DIR);
            },
            filename: (req, file, cb) => {
              // implement getLoggedInUser() method which basically returns the current logged in user
                 cb(null, file.fieldname + '-' + Date.now()+ getLoggedInUser())
            },
        });
        //upload end point
        app.post('/upload', upload.array('uploads[]', 12), (req, res) => {
            console.log(req.files);
    
    
            if (req.files.length <= 0) {
                res.status(404).send({ message: 'no file recieved' });
            } else {
             fs.readdirSync(DIR).forEach((file)=>{
    
             let path=path.join(DIR,file);
             let fileSchema= new FileSchema(path);
             fileSchema.save((err,result)=>{
               if (err) {
                 throw new Error({ message: 'user is not saved', status: 500 });
               }
              res.status(200).send({ message: 'file successfully saved' });
             });
           });
         }
        });
    

    从您的 Angular 应用程序中,您可以创建一个服务并将其注入到您的表单组件中

    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs';
    import { HttpClient, HttpHeaders } from '@angular/common/http'
    import { map } from 'rxjs/operators';
    
    @Injectable({
      providedIn: 'root'
    })
    export class UploadService {
      static API_URL: string = '<url for your upload end point>';
      constructor(private http: HttpClient) { }
    
      fileUpload(files: any): Observable<Object> {
        const formData: any = new FormData();
        const fileArray: Array<File> = files;
        for (let i = 0; i < fileArray.length; i++) {
          formData.append('uploads[]', fileArray[i], fileArray[i]['name']);
        }
        return this.http.post(UploadService.API_URL + 'upload', formData)
          .pipe(
            map(x => {
              return x;
            })
          );
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多