How can i blog component in Angular?
我想在Angular中制作一个以Nodejs为后端的博客组件,
博客结构包含:图像和描述,我想在单个事件中将其上传到后端(nodejs 和 mongodb)。
主要关注的是如何在一个事件中将图像及其描述一起上传到后端。
- 就像在 Angular 中从任何形式发送数据一样,你使用模型来跟踪它?
- 但是我想发送带有表单数据的图像并想使用 multer 但这不会发生在单个请求中
- 这将帮助您发布表单数据
- @MuhammadShareyar,但我还想发送一些文本数据,例如带有图像的标题
这是一个简单的例子。
1
2 3 4 5 6 7 8 9 10 |
<form
[formGroup]=”angForm” novalidate (submit)=”createBlog(angForm)” enctype=”multipart/form-data”> <textarea class=”form-control form-control-lg” placeholder=”Create a post” formControlName=”data” #data ></textarea> <inpu type=”file” name=”image” name=”image” #image (change)=”onFileSelect($event)”/> <button type=”submit class=”btn btn-dark” [disabled]=”angForm.pristine || angForm.invalid”> Submit</button> </form> |
这是一个简单的 angular reactive form,我们用来验证所需的字段,我们定义了 onFileSelect() 函数来更改输入值,我们将使用它来保存 formData
blog.ts 文件
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
import { FormBuilder, FormGroup, Validators } from”@angular/forms”;
angForm: FormGroup; //our constructor //reactive form group and set validations for required field createBlog(form) { this.http //on change event we append file to formdata |
要在nodejs中保存文件,你需要使用multer包和body-Parser来保存文本数据
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
const multer = require(“multer”);
const upload = multer({ dest:”public/images/” }); //desired path to save file //your post route to save data router.post(“/create”,upload.single(“file”),(req, res) => { if (req.file) { //creating instance of new blog const newBlog = new Blog({ desc: req.body.data, image: req.file.filename }); //save blog data and image name into db |
- 你能给我一个这个代码的链接吗? PS this.createForm() 在构造函数中也给出了错误
- FormData() 没有附加多个文件@MuhammadShareyar
- 对于多个文件,您需要将其命名为表单中的数组,例如 name=image[]
- 甚至文件上的设置值也给出错误:无法在 HTMLInputElement 上设置值属性:此输入元素接受文件名,该文件名只能以编程方式设置为空字符串。
- 当我选择文件时
- 您是否在 input 标签中添加了 multiple 属性 <input type=”file” name=”image” name=”image” #image (change)=”onFileSelect($event)” multiple > 这样做并检查它是否可以正常工作,然后@ShivaChandel
- 它没有用,仍然给出与上述相同的错误
- 让我们在聊天中继续这个讨论。
来源:https://www.codenong.com/55824068/