【发布时间】: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