【问题标题】:Save file to mongodb using angular and Nodejs使用 Angular 和 Nodejs 将文件保存到 mongodb
【发布时间】:2018-10-30 04:05:05
【问题描述】:

我正在尝试使用 angular 和 nodejs 将图像上传到 mongodb。代码如下。我得到了后端工作,但问题是我得到'C:fakepath/file.xyz'的html输入。我在网上看,发现没有办法获取文件的相对路径。有人可以告诉我如何更改我的前端代码以获取文件路径并将其发送到后端然后保存。我读到浏览器不允许文件的相对路径,但是我该如何上传。谢谢!

nodejs图片保存方式为:

 async function SaveImage(userParam) {
    const entry = new imageEntries(userParam);
    entry.image.data = fs.readFileSync(userParam.imagePath);
    entry.image.contentType = 'image/png';
    await entry.save();
    }

html代码为:

<div class="upload-btn-wrapper">
  <button class="btn">Upload a file</button>
  <input type="file" name="myfile" id="myFile" />
</div>

我在后端传递的路径是:

ImageJournal.imagePath = (<HTMLInputElement>document.getElementById('myFile')).value;

但是使用上面的代码我得到以下错误:

ENOENT: no such file or directory, open 'C:\fakepath\chapter9problemsandanswers.doc'

【问题讨论】:

  • 可以使用formData存储输入文件,然后通过http.post发送。另一种方法是对图像进行 base64 编码,然后将其作为字符串发送到服务器。然后,服务器可以将其存储为字符串。当您检索它时,您可以将其从 base64 转换为图像并下载或显示。我不认为通过路径会起作用。生产环境中的服务器将无法从您的系统中读取文件。您需要自己发送文件。
  • @GiwrgosLampadaridis 感谢您的回复,您能提供一个我的例子吗?这意味着我将不得不更改我的后端代码方法,对吗?
  • 是的,你有。我目前正在使用手机,大约一个小时后我会向您发送样品

标签: node.js angular mongodb image-uploading


【解决方案1】:

好的,就是这样:

HTML:

<div class="form-group">
      <label for="pdf">PDF</label>
      <input type="file" id="pdf" (change)="onFileChange($event)" #fileInput>
      <button type="button" class="btn btn-sm btn-default" (click)="clearFile()">clear file</button>
</div>

TS:

import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
@ViewChild('fileInput') fileInput: ElementRef;
public image;

 onFileChange(event) {
    let reader = new FileReader();
    if(event.target.files && event.target.files.length > 0) {
      let file = event.target.files[0];
      reader.readAsDataURL(file);
      let value = <String>reader.result;
      reader.onload = () => {
        this.image = {
          filename: file.name,
          filetype: file.type,
          value: value.split(',')[1]
        };
      };
    }
  }

然后通过服务发送带有 http post 的图像。 在服务器上:

//发送文件

app.post('/api/sendFile', function (req, res) {
    File.create({
        filename: req.body.filename,
        filetype: req.body.filetype,
        value: req.body.value
    }, function (err, file) {
        if (err)
            res.send(err);
        else {
            const response = {
                name: file.filename
            }
            res.send(response);
        }
    });
});

这是用 mongoDb 和 mongoose 编写的,我有一个名为 File 的模型。 这就是保存它所需要的全部内容。

【讨论】:

  • 还有,一旦我从后端检索它,我将如何将其转换回图像
猜你喜欢
  • 1970-01-01
  • 2019-11-03
  • 1970-01-01
  • 2015-05-21
  • 1970-01-01
  • 2018-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多